将参数传递给 powershell 中的脚本块 [英] Pass arguments to a scriptblock in powershell

查看:53
本文介绍了将参数传递给 powershell 中的脚本块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想你不能只是这样做:

I guess you can't just do this:

  $servicePath = $args[0]

  if(Test-Path -path $servicePath) <-- does not throw in here

  $block = {

        write-host $servicePath -foreground "magenta"

        if((Test-Path -path $servicePath)) { <-- throws here.

              dowork 
        }
  }

那么如何将我的变量传递给脚本块 $block?

So how can I pass my variables to the scriptblock $block?

推荐答案

Keith 的回答 也适用于 Invoke-Command,有不能使用命名参数的限制.参数应使用 -ArgumentList 参数设置,并应以逗号分隔.

Keith's answer also works for Invoke-Command, with the limit that you can't use named parameters. The arguments should be set using the -ArgumentList parameter and should be comma separated.

$sb = {
    param($p1,$p2)
    $OFS=','
    "p1 is $p1, p2 is $p2, rest of args: $args"
}
Invoke-Command $sb -ArgumentList 1,2,3,4

另请参阅此处此处.

这篇关于将参数传递给 powershell 中的脚本块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆