分类 备忘 下的文章

  • When extracting files from git stash (you can see here for more details) in Powershell, you may encounter a strange error which says error: unknown switch `e'.
    It is caused by the {} character in Powershell: these braces are parsed unexpectedly. Use ` symbol to escape them: git checkout stash@{0} -- /path/to/your/file
  • Rollback to any commit that you have ever committed:

    git reflog
    git reset HEAD@{index}
  • Update your commit RIGHT after it has been committed:

    git add .
    git commit --amend --no-edit # the commit will now contains what you have added
  • Change the message of my last commit: git commit --amend
  • move a just-committed one to a new branch
    If you committed to master/main:

    # create a new branch from the current state of master
    git branch some-new-branch-name
    # remove the last commit from the master branch
    git reset HEAD~ --hard
    git checkout some-new-branch-name

    If you committed to another branch:

    git checkout name-of-the-correct-branch
    # grab the last commit to master
    git cherry-pick master
    # delete it from master
    git checkout master
    git reset HEAD~ --hard

Reference

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