Cheatsheets

设置代理

PS C:\> $Env:HTTP_PROXY="http://localhost:7890"
PS C:\> $Env:HTTPS_PROXY="http://localhost:7890"

grep equivalent - Select-String

  • Simple Matching
    Select-String -Path "Users\*.csv" -Pattern "Joe"
  • Multi-Pattern Matching
    Select-String -Path "Users\*.csv" -Pattern "Joe","Marti","Jerry"
  • RegEx with head equivalent
    Select-String -Path "Users\*.csv" -Pattern '\\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b' | Select-Object -First 10
  • Recursively search csharp src files
    Get-ChildItem -Recurse *.cs | Select-String -Pattern 'keyword'

rm equivalent - Remove-Item

可以直接用,但是需要注意,rm -rf 等价于 Remove-Item -Recurse -Force,shell的参数不能直接用。

wget and curl equivalent - Invoke-WebRequest

下载文件这么写:Invoke-WebRequest -v https://path/to/file.exe -OutFile ./file.exe
如果想按照原来的名字呢?不幸地,你需要自己实现一个函数。当然你可以把函数像用bash一样保存在一个profile文件里,这个profile的路径可以用notepad $profile直接打开:

Function My-Download {
  param ( [parameter(position=0)]$uri )
  Invoke-WebRequest -uri $uri -OutFile $(Split-Path -path "$uri" -leaf)
}

Troubleshooting

标记“&&”不是此版本中的有效语句分隔符。

对Windows自带的5.1版PS,不支持&&操作符,需要这么用:

(command_1) -and (command_2)

如果不需要短路特性可以简单的使用分号隔开。
新版(Powershell 7以上)可以使用&&

一句话问题

  • 命令补全感觉怪怪的:需要让它学bash,但是只有新版可以。在profile(上文提到过路径)里这么添加:

    Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete
  • 帮助文件下不下来:先考虑代理,如果在Windows中设置netsh winhttp set proxy "127.0.0.1:7890",在Linux/Mac中设置http{,s}_proxy(要在运行前通过env设置,不要进入powershell内设置);再运行Update-Help -UICulture en-US

标签: 脚本

添加新评论