Reputation: 1
What I have is a powershell script running in order to check differences in commits between two git branches. Here's what I'm fetching from git expression:
$result = Invoke-Expression "& git rev-list --left-right --count origin/$TargetBranch...origin/$SourceBranch 2>&1"
Unfortunately I have found out that when $SourceBranch
contains '
character it throws an
[error]At line:1 char:143 + ..._move_to_record_icon_doesn't_respond 2>&1
The string is missing the terminator: '.
I have implemented escaping of special characters like this:
[System.Text.RegularExpressions.Regex]::Escape($SourceBranch)
then $SourceBranch.replace('\','`')
But it does not escape the '
character, putting it into replace("'","`'")
does not work either.
Powershell 5.0 used.
Upvotes: 0
Views: 529
Reputation: 1169
You need to escape a escape character itself.
An example to run a'b.bat
in PowerShell,
# create filename containing '
echo "echo 1" | Set-Content -Encoding Ascii "a'b.bat"
# double quote
Invoke-Expression ".\a``'b.bat"
Invoke-Expression ".\a''''b.bat"
# single quote
Invoke-Expression '.\a`''b.bat'
Invoke-Expression '.\a''''''''b.bat'
# with -replace operator
$source = ".\a'b.bat"
Invoke-Expression "cmd /c $($source -replace "'", "''''" )"
This may look strange, but it's just the same as
JSON.stringify({a: "\\"}) === "{\"a\":\"\\\\\"}"
in JavaScript.
but it's much easier without using Invoke-Expression as already answered.
& ".\a'b.bat"
& '.\a''b.bat'
Upvotes: 0
Reputation: 174485
Just avoid Invoke-Expression
altogether:
$result = & git rev-list --left-right --count origin/$TargetBranch...origin/$SourceBranch 2>&1
Upvotes: 1