[英]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. 我正在运行以下Powershell命令,并且2个“test”之间的双空格被转换为单个空格。 Using PS 3.0. 使用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: 下面的脚本调用(只包含$ String参数和Write-Host $ String;暂停)工作正常,但在同一会话中执行:
& 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. 我需要能够在当前会话之外运行另一个PS脚本,并将参数传递给可能包含这样的双空格的脚本。 Thank you! 谢谢!
As far as I can tell, this is happening because double quotes are not being put around the arguments before being sent to PowerShell. 据我所知,这种情况正在发生,因为在发送到PowerShell之前,双引号没有放在参数周围。 That would cause the shell to collapse the spaces (as it parses arguments) before PowerShell ever sees them. 这将导致shell在PowerShell看到它们之前折叠空间(因为它解析参数)。
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: 所以在新推出的PowerShell窗口中,我运行了这个:
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). shell似乎并不关心单引号,因此命令中的每个空格都会让shell认为它是一个新参数(它基本上是在空格上分裂,所以多个连续的空格都会折叠,除非它看到一个双引号字符串,被视为单个参数)。
You can fix it by embedding quotes yourself. 您可以通过自己嵌入引号来修复它。
Start-Process Powershell -ArgumentList "`"Write-Host 'test test';pause`""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.