2

我有一个非常简单的 Powershell v1.0 脚本来按名称杀死进程:

$target = $args[0]
get-process | where {$_.ProcessName -eq $target} | stop-process -Force

哪个有效。然而,当我刚刚

get-process | where {$_.ProcessName -eq $args[0]} | stop-process -Force

它不会找到任何进程。那么为什么需要将参数复制到局部变量中才能使代码正常工作呢?

4

1 回答 1

5

这是昨天在另一篇文章中提出的。基本上一个脚本块{ <script> }有它自己的 $args 代表传入它的未命名参数,例如:

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

Where-Object cmdlet 使用脚本块为您提供任意脚本,它评估为真或假。在 Where-Object 的情况下,没有传递给脚本块的未命名参数,因此 $args 应该为空。

您找到了一种解决方法。我建议的是使用命名参数,例如:

param($Name, [switch]$WhatIf)
get-process | where {$_.Name -eq $Name} | stop-process -Force -WhatIf:$WhatIf
于 2010-03-04T16:38:01.870 回答