I want to pass from a PowerShell script to an external (CygWin) program arguments (file paths), which contain arbitrary characters, including single quotes, double quotes, backslashes, spaces, and non-ASCII characters. Through some obscure ways, single and double quotes go missing and the recommended quoting mechanism isn't enough to fix the problem. Specifically, double quotes at the beginning of the string get replaced by a backslash, single quotes at the beginning or end of the string get lost, and single quotes interfere with non-ASCII characters in unpredictable ways.
As an example, consider this echo-first.sh
sh shell script, which echoes its first argument.
#!/bin/sh
echo "$1"
Here is the output of Windows PowerShell (5.1) when I run the script with various arguments, each prefixed with a comment indicating whether the output is correct or not.
# OK: hello world
bash ./echo-first.sh "hello world"
# Not OK: double
bash ./echo-first.sh 'double " quote'
# Not OK: double quoted
bash ./echo-first.sh '"double quoted"'
# OK: double " quote
bash ./echo-first.sh ('double " quote' -replace '"', '\"')
# Not OK: \double quoted"
bash ./echo-first.sh ('"double quoted"' -replace '"', '\"')
# OK: A "double quoted" phrase
bash ./echo-first.sh ('A "double quoted" phrase' -replace '"', '\"')
# OK: single ' quote
bash ./echo-first.sh "single ' quote"
# OK: 'single quoted'
bash ./echo-first.sh "'single quoted'"
# Not OK: [no output]
bash ./echo-first.sh "'"
# Not OK: [no output]
bash ./echo-first.sh "''"
# OK: ''
Write-Output "''"
# OK: αβ''γ
bash ./echo-first.sh "αβ''γ"
# Not OK: αβγδ
bash ./echo-first.sh "αβγ''δ"
# OK: αβγδεζηθικλμ
bash ./echo-first.sh "αβγδεζηθικλμ"
# Not OK: αβγδεζηθικλμ#
bash ./echo-first.sh "αβ''γδεζηθικλμ"
# Major Minor Build Revision
# ----- ----- ----- --------
# 5 1 18362 145
Write-Output $PSVersionTable.PSVersion