为什么PowerShell无法识别带引号的参数? [英] Why does PowerShell not recognize quoted parameters?
问题描述
为什么直接调用脚本(在PowerShell控制台或ISE中)或通过另一个PowerShell实例调用脚本时,PowerShell会对引号参数进行不同的处理?
Why does PowerShell treat quoted parameters differently when you invoke the script directly (in a PowerShell console or ISE) or when you invoke it via another PowerShell instance?
这是脚本(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
有什么想法吗?
推荐答案
According to the PowerShell.exe Command-Line Help, the first argument for the powershell
executable is -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.
Any text after
-Command
is sent as a single command line to PowerShell.
...
当-Command
的值为字符串时,Command
必须是指定的最后一个参数,因为在命令后键入的任何字符都将解释为命令参数.
When the value of -Command
is a string, Command
must be the last parameter specified because any characters typed after the command are interpreted as the command arguments.
通过 echoargs :
PS > echoargs .\TestQuotes.ps1 -Config "A B C"
Arg 0 is <.\TestQuotes.ps1>
Arg 1 is <-Config>
Arg 2 is <A B C>
子实例将其进一步解析为:
Which is further parsed by the child instance to:
'.\TestQuotes.ps1' '-Config' 'A' 'B' 'C'
这是您得到错误"结果的地方:Config = A
And this is where you get your "wrong" result: Config = A
如果指定-File
自变量,则将获得所需的结果:
If you specify -File
argument, you'll get the desired result:
PS > PowerShell -File .\TestQuotes.ps1 -Config 'A B C'
Config = A B C
PS > PowerShell -Command .\TestQuotes.ps1 -Config 'A B C'
Config = A
这篇关于为什么PowerShell无法识别带引号的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!