Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell argumentlist and double+ spaces

Would someone be able to explain this? I'm running the following Powershell commands and the double spaces between the 2 "test"s are converted into a single space. Using PS 3.0.

Start-Process Powershell -ArgumentList "-Command Write-Host test  test;pause"
Start-Process Powershell -ArgumentList "-Command Write-Host 'test  test';pause"
Start-Process Powershell -ArgumentList "Write-Host 'test  test';pause"

The script call below (which just contains a $String param and the Write-Host $String;pause) works fine, but executes in the same session:

& C:\Test\Test.ps1 -String 'test  test'

But the below replaces the double spaces with a single:

Start-Process Powershell -ArgumentList "& C:\Test\Test.ps1 -String 'test  test'"

I need to be able to run another PS script outside the current session and pass arguments to the script that might include double spaces like these. Thank you!

like image 713
atownson Avatar asked Aug 06 '15 02:08

atownson


1 Answers

As far as I can tell, this is happening because double quotes are not being put around the arguments before being sent to PowerShell. That would cause the shell to collapse the spaces (as it parses arguments) before PowerShell ever sees them.

So I tried this test:

Start-Process powershell.exe -ArgumentList "-NoExit -Command Write-Verbose '1 2  3   .' -Verbose"

It failed like yours did, no spaces.

So in the newly minted PowerShell window, I ran this:

gwmi Win32_Process -Filter "ProcessId = '$([System.Diagnostics.Process]::GetCurrentProcess().Id)'" | select -ExpandProperty CommandLine

The result:

"C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit -Command Write-Verbose '1 2  3   .' -Verbose 

See how there are no double quotes around the command? The shell doesn't seem to care about the single quotes, so every space in your command makes the shell think it's a new argument (it's basically splitting on spaces, so multiple consecutive spaces get collapsed, unless it sees a double quoted string, which is treated as a single argument).

You can fix it by embedding quotes yourself.

Start-Process Powershell -ArgumentList "`"Write-Host 'test  test';pause`""
like image 149
briantist Avatar answered Oct 13 '22 00:10

briantist