gijs007
gijs007

Reputation: 233

Get-WmiObject : A positional parameter cannot be found that accepts argument

I've created the following PowerShell script to kill a process:

$oProcs = Get-WmiObject Win32_Process -filter "commandline like '%G:\\TCAFiles\\Users\\Admin\\2155\\Unturned.exe%'";foreach ($oProc in $oProcs){Stop-Process $oProc.Handle}

The above script works fine, however when I'm trying to make the script start from Command Prompt it fails.

powershell -Mta -NoProfile -Command "$oProcs = Get-WmiObject Win32_Process -filter "commandline like '%G:\TCAFiles\Users\Admin\2155\Unturned.exe%'";foreach ($oProc in $oProcs){Stop-Process $oProc.Handle}"

This results in the following error:

Get-WmiObject : A positional parameter cannot be found that accepts argument
'%G:\TCAFiles\Users\Admin\2155\Unturned.ex e%'.
At line:1 char:11
+ $oProcs = Get-WmiObject Win32_Process -filter commandline like '%G:\T ...
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WmiObject], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetWmiObjectCommand

I'm not sure what this error means or how to resolve it.

Upvotes: 1

Views: 5006

Answers (1)

Chris Barber
Chris Barber

Reputation: 513

You will need to escape any double quotes inside the powershell code that you are passing as an argument. At the moment your command argument will end after "-filter ".

If you are running this from cmd you can escape the double quotes using a backslash:

powershell -Mta -NoProfile -Command "$oProcs = Get-WmiObject Win32_Process -filter \"commandline like '%G:\TCAFiles\Users\Admin\2155\Unturned.exe%'\";foreach ($oProc in $oProcs){Stop-Process $oProc.Handle}"

Or if you are running this in powershell you can escape them by prepending it with a backtick or another double quote:

powershell -Mta -NoProfile -Command "$oProcs = Get-WmiObject Win32_Process -filter ""commandline like '%G:\TCAFiles\Users\Admin\2155\Unturned.exe%'"";foreach ($oProc in $oProcs){Stop-Process $oProc.Handle}"

Upvotes: 2

Related Questions