为什么需要将 PowerShell 脚本参数复制到局部变量?
我有一个非常简单的 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
它找不到任何进程。那么为什么需要将参数复制到局部变量中才能使代码正常工作呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是昨天在另一个 发布。基本上是一个脚本块
{
Where-Object cmdlet 使用脚本块为您提供任意脚本,该脚本的计算结果为 true 或 false。在Where-Object 情况下,没有未命名的参数传递到脚本块中,因此 $args 应为空。
您已找到一种解决方法。我建议的是使用命名参数,例如:
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.: