Search code examples
gitpowershellescapingfreezetilde

System.Diagnostics.ProcessStartInfo hangs if the arguments include a tilde mark


The git command git reset HEAD~ will undo the last commit. But when I try and run the command in PowerShell using System.Diagnostics.ProcessStartInfo, the process just hangs.

I think it has something to do with the tilde (~) mark, because I tried to escape it with a backslash and the command didn't hang anymore. But it didn't work, either. It just silently failed.

Here is the script:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "C:\Program Files\Git\cmd\git.exe"
$pinfo.Arguments = "reset HEAD~"
$pinfo.WorkingDirectory = "C:\GitRepo"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.CreateNoWindow = $true

$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()

Solution

  • Passing the arguments as a list seems to fix it:

    $pinfo.Arguments = "reset","HEAD~"
    

    I guess there's some more auto escaping going on with this method.