Search code examples
powershellcmdescapingquoting

Running PowerShell command from CMD gives positional parameter error


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?


Solution

  • 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.