开发者

Why did a PowerShell script argument need to be copied to a local variable?

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 开发者_如何学Gowork?


This came up yesterday in another post. Basically a scriptblock { <script> } gets its own $args that represents unnamed arguments passed into it e.g.:

PS> & { $OFS=', '; "`$args is $args" } arg1 7 3.14 (get-date)
$args is arg1, 7, 3.14, 03/04/2010 09:46:50

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

param($Name, [switch]$WhatIf)
get-process | where {$_.Name -eq $Name} | stop-process -Force -WhatIf:$WhatIf
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜