Skip to content

Instantly share code, notes, and snippets.

@piscisaureus
Last active September 25, 2018 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piscisaureus/785526268f6742fd0937f74928372cf9 to your computer and use it in GitHub Desktop.
Save piscisaureus/785526268f6742fd0937f74928372cf9 to your computer and use it in GitHub Desktop.
Shell quote/unquote command Line Powershell
function BuildCommandLine([string[]] $ArgumentList) {
$special_chars = '[\x00-\x20"^%~!@&?*<>|()\\=]'
$quoted_args = $ArgumentList | foreach {
if ($_ -match $special_chars) {
# Double all double-quote characters.
$_ = $_ -replace '"', '""'
# Wrap in double-quote characters.
$_ = """$_"""
# Double all backslashes that are followed by \.
$_ = $_ -replace '[\\]+(?=")', '$0$0'
}
$_
}
$quoted_args -join " "
}
# PowerShell equivalent of CommandLineToArgvW.
# https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-commandlinetoargvw
function ParseCommandLine([string] $CommandLine) {
$CommandLine | foreach {
$arg = $null # Argument currently being built by the parser.
$q = $false # True when parsing a quoted substring (between ").
for (; $_ -or $arg -ne $null; $_ = $_.Remove(0, $Matches[0].Length)) {
if ($_ -match '^(\\\\)+(?=\\?")') { # Backslashes are escaped
$arg += '\' * ($Matches[0].Length/2) # as \\, but only before ".
} elseif ($_ -match '^\\"' -or ($q -and $_ -match '^""')) {
$arg += '"' # Quotes are escaped as \", in quoted str also "".
} elseif ($_ -match '^"') {
$q = -not $q # Unescaped quote: begin/end of quoted substring.
$arg += '' # Empty args happen; if $arg is null, change to ''.
} elseif ($_ -match '^$' -or (-not $q -and $_ -match '^[ `t]+')) {
$arg # End of cmd, or space/tab outside quotes: emit arg.
$arg = $null # Init next arg. Note: null $arg += 'string' is ok.
} elseif ($_ -match '^.') {
$arg += $Matches[0] # Char w/o special purpose: append to arg.
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment