通过管道传递脚本块 [英] Passing a scriptblock through pipeline

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

问题描述

我可以通过管道传递脚本块吗?例如,代替

Can I pass a scriptblock through the pipeline? For example, instead of

Invoke-Command -ScriptBlock {Get-Job}

我可以(从概念上)执行以下操作吗?

Can I do (conceptually) the following?

{Get-Job} | Invoke-Command -ScriptBlock $_

推荐答案

当然可以.$_(又名 $PSItem)在诸如 ForEach-ObjectWhere-Object 之外是无效的> 不过.所以你必须这样做:

Sure, you can. $_ (aka $PSItem) isn't valid outside of something such as ForEach-Object or Where-Object though. So you'd have to do this:

# % is the default alias (short-hand) for ForEach-Object
{ Get-Process } | % { Invoke-Command -ScriptBlock $_; };

你也可以传递一组 $ScriptBlock 对象,像这样:

You can also pass an array of $ScriptBlock objects, like this:

{ Get-Process }, { Start-Sleep -Seconds 2 }, { Get-ChildItem } | ForEach-Object -Process { Invoke-Command -ScriptBlock $PSItem; };

注意前面的代码:

  1. 获取进程列表
  2. 睡眠两 (2) 秒
  3. 获取当前路径下的子项列表

ForEach-Object 上的 -Process 参数是第一个"参数,因此通常您不必指定参数的名称.为了清楚起见,我确实指定了完整的 ForEach-Object cmdlet 名称并在第二个示例中添加了 -Process 参数名称.

The -Process parameter on ForEach-Object is the "first" parameter, so normally you don't have to specify the parameter's name. I did specify the full ForEach-Object cmdlet name and added the -Process parameter name in the second example for the sake of clarity.

这里是我们声明 ScriptBlock 对象的 Array 的示例.然后,我们将包含 ScriptBlock 对象的数组变量通过管道传输到 ForEach-Object.它与上面的想法相同,但单独声明数组.但请记住,如果您使用 ForEach-Object,则必须使用 -Process 参数,而不是 -Begin-End 参数,因为这些参数在每次调用 ForEach-Object 时只运行一次.

Here is an example where we declare an Array of ScriptBlock objects. Then, we pipe the array variable, containing the ScriptBlock objects into ForEach-Object. It's the same idea as above, but declaring the array separately. Remember though, if you're using ForEach-Object, you must use the -Process parameter, not the -Begin or -End parameters, because those only run once per call to ForEach-Object.

$ScriptBlockList = @(
    { Get-Process; };
    { Start-Sleep -Seconds 5; };
    { Start-Job -ScriptBlock { Get-Process; }; };
    );

$ScriptBlockList | ForEach-Object -Process { Invoke-Command -ScriptBlock $PSItem; };

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

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