【问题标题】:Running PowerShell command from CMD gives positional parameter error [duplicate]从 CMD 运行 PowerShell 命令会导致位置参数错误 [重复]
【发布时间】:2019-04-17 18:03:17
【问题描述】:

我有这个 PowerShell 命令:

Get-WmiObject -Query "Select * from CIM_DataFile Where Extension = 'ost'" |
    Select-Object 'Name' |
    Out-File C:\temp\ost.txt -Append

但我需要在命令提示符下运行它。我是这样运行的:

powershell.exe -ExecutionPolicy ByPass -Command "Get-WmiObject -Query "Select * from CIM_DataFile Where Extension = 'ost'" | Select-Object 'Name' | Out-File C:\temp\ost.txt -Append"

我收到此错误:

Get-WmiObject:找不到接受参数“*”的位置参数。 在行:1 字符:1 + Get-WmiObject -Query Select * from CIM_DataFile Where Extension = 'os ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ParameterBindingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetWmiObjectCommand

如何正确运行?

【问题讨论】:

  • -Query 参数使用单引号,并使用^ 转义双引号。
  • 用反斜杠转义嵌套的双引号:"Get-WmiObject -Query \"Select * from ...\" | ..."
  • @AnsgarWiechers 为什么是\?我以为cmd 转义是^
  • 别问我为什么。我只能告诉你^ 是 CMD most 中的转义字符。 ;)
  • @TheIncorrigible1: PowerShell 需要\ -转义" 字符。 在处理 CLI 参数时cmd.exe 忽略了 \ 本身,尽管它将以下 " 视为语法元素然后带来了自己的挑战。

标签: powershell cmd escaping quoting


【解决方案1】:

您必须转义 嵌套 " 字符。在你的命令中,这是最稳健的\""(原文如此):

PowerShell.exe -c  "Get-WmiObject -Query \""Select * ... 'ost'\"" | Select ..."

警告\""powershell.exe (和pwsh 用于PowerShell Core)效果良好且稳健,但不适用于other 程序,例如 pythonrubyperlnode

请参阅linked answer 了解详细说明,包括如何为其他程序转义。

【讨论】:

    猜你喜欢
    • 2021-07-05
    • 2019-10-25
    • 1970-01-01
    • 2021-01-05
    • 2023-03-14
    • 2018-03-14
    • 2021-07-17
    • 2021-09-13
    • 1970-01-01
    相关资源
    最近更新 更多