简体   繁体   中英

Running PowerShell command from CMD gives positional parameter error [duplicate]

This question already has an answer here:

I have this PowerShell command:

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

But I need to run it form a command prompt. I'm running it like this:

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"

I'm getting this error:

Get-WmiObject : A positional parameter cannot be found that accepts argument '*'.
At line:1 char:1
+ Get-WmiObject -Query Select * from CIM_DataFile Where Extension = 'os ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WmiObject], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetWmiObjectCommand

How do I run this correctly?

You must escape the nested " chars. in your command, which is most robustly done as \\"" (sic):

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

Caveat : Use of \\"" works well and robustly with powershell.exe , (and pwsh for PowerShell Core ) but not with other programs, such as python , ruby , perl or node .

See the linked answer for a detailed explanation, including how to escape for other programs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM