mles
mles

Reputation: 3466

Escaping args[0] in Powershell

I'm writing a script to terminate a process identified by it's Commandline call. It works fine if i hardcode it like:

Get-WmiObject Win32_Process -Filter "CommandLine LIKE '%worker04%'" | Invoke-WmiMethod -Name Terminate

Now I want to work with a parameter like this:

Get-WmiObject Win32_Process -Filter "CommandLine LIKE '%$args[0]%'" | Invoke-WmiMethod -Name Terminate

so I can call my script like this:

.\killprocess worker04

So far it does nothing. How do I correctly put the $args[0] in the -Filter block?

Upvotes: 1

Views: 382

Answers (2)

MarcinSZ
MarcinSZ

Reputation: 11

I got the same problem in the for loop and %$($args[0])% does not work for me. I made it with something like that:

for($i; $i -lt $args.length ;$i++)
{
$arg=$args[$i]
Get-WmiObject Win32_Process -Filter "CommandLine LIKE '$arg'...... 
}

It works fine here.

Upvotes: 1

Musaab Al-Okaidi
Musaab Al-Okaidi

Reputation: 3784

I think this will do it:

Get-WmiObject Win32_Process -Filter "CommandLine LIKE '%$($args[0])%'" | Invoke-WmiMethod -Name Terminate

Upvotes: 3

Related Questions