I have a very simple Powershell v1.0 script to kill processes by name:
$target = $args[0]
get-process | where {$_.ProcessName -eq $target} | stop-process -Force
which works. However, when I just had
get-process | where {$_.ProcessName -eq $args[0]} | stop-process -Force
it wouldn’t find any processes. So why does the argument need to be copied into a local variable for the code to work?
This came up yesterday in another post. Basically a scriptblock
{ <script> }gets its own $args that represents unnamed arguments passed into it e.g.:The Where-Object cmdlet is using a scriptblock for you to provide arbitrary script which it evaluates to either true or false. In the Where-Object case, there are no unnamed arguments passed into the scriptblock so $args should be empty.
You’ve found one work-around. The one I would suggest is to use a named parameter e.g.: