为什么需要将PowerShell脚本参数复制到局部变量?

Cha*_*son 2 powershell powershell-1.0

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

$target = $args[0]
get-process | where {$_.ProcessName -eq $target} | stop-process -Force
Run Code Online (Sandbox Code Playgroud)

哪个有效.但是,当我刚才

get-process | where {$_.ProcessName -eq $args[0]} | stop-process -Force
Run Code Online (Sandbox Code Playgroud)

它找不到任何流程.那么为什么需要将参数复制到局部变量中以使代码工作?

Kei*_*ill 5

这是昨天在另一篇文章中提出的.基本上,一个scriptblock { <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
Run Code Online (Sandbox Code Playgroud)

Where-Object cmdlet使用scriptblock为您提供任意脚本,并将其评估为true或false.在Where-Object的情况下,没有未命名的参数传递到scriptblock中,因此$ args应为空.

你找到了一个解决方法.我建议的是使用命名参数,例如:

param($Name, [switch]$WhatIf)
get-process | where {$_.Name -eq $Name} | stop-process -Force -WhatIf:$WhatIf
Run Code Online (Sandbox Code Playgroud)