当您直接调用脚本(在 PowerShell 控制台或 ISE 中)或通过另一个 PowerShell 实例调用脚本时,为什么 PowerShell 对带引号的参数的处理方式有所不同?
这是脚本(TestQuotes.ps1
):
param
(
[string]
$Config = $null
)
"Config = $Config"
结果如下:
PS D:\Scripts> .\TestQuotes.ps1 -Config "A B C"
Config = A B C
PS D:\Scripts> PowerShell .\TestQuotes.ps1 -Config "A B C"
Config = A
PS D:\Scripts> .\TestQuotes.ps1 -Config 'A B C'
Config = A B C
PS D:\Scripts> PowerShell .\TestQuotes.ps1 -Config 'A B C'
Config = A
有任何想法吗?
根据PowerShell.exe 命令行帮助 https://learn.microsoft.com/en-us/powershell/scripting/components/console/powershell.exe-command-line-help,第一个参数powershell
可执行文件是-Command
:
PowerShell[.exe]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
[-EncodedCommand <Base64EncodedCommand>]
[-ExecutionPolicy <ExecutionPolicy>]
[-File <FilePath> [<Args>]]
[-InputFormat {Text | XML}]
[-Mta]
[-NoExit]
[-NoLogo]
[-NonInteractive]
[-NoProfile]
[-OutputFormat {Text | XML}]
[-PSConsoleFile <FilePath> | -Version <PowerShell version>]
[-Sta]
[-WindowStyle <style>]
PowerShell[.exe] -Help | -? | /?
之后的任何文字-Command
作为单个命令行发送到 PowerShell。
...
当值为-Command
是一个字符串,Command
必须是最后指定的参数,因为命令后键入的任何字符都被解释为命令参数.
子 PowerShell 实例实际收到的内容很容易检查echoargs https://chocolatey.org/packages/echoargs:
PS > echoargs .\TestQuotes.ps1 -Config "A B C"
Arg 0 is <.\TestQuotes.ps1>
Arg 1 is <-Config>
Arg 2 is <A B C>
子实例进一步解析为:
'.\TestQuotes.ps1' '-Config' 'A' 'B' 'C'
这就是你得到“错误”结果的地方:Config = A
如果您指定-File
参数,你会得到想要的结果:
PS > PowerShell -File .\TestQuotes.ps1 -Config 'A B C'
Config = A B C
PS > PowerShell -Command .\TestQuotes.ps1 -Config 'A B C'
Config = A
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)