为什么PowerShell无法识别带引号的参数? [英] Why does PowerShell not recognize quoted parameters?

查看:165
本文介绍了为什么PowerShell无法识别带引号的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么直接调用脚本(在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆