PowerShell的 - 如何美元的启动工作一个脚本块p $ P-评估变量 [英] Powershell - how to pre-evaluate variables in a scriptblock for Start-Job

查看:208
本文介绍了PowerShell的 - 如何美元的启动工作一个脚本块p $ P-评估变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在PowerShell中使用的后台作业。

I want to use background jobs in Powershell.

如何使在脚本块定义的时刻评估变量?

How to make variables evaluated at the moment of ScriptBlock definition?

$v1 = "123"
$v2 = "asdf"

$sb = {
    Write-Host "Values are: $v1, $v2"
}

$job = Start-Job -ScriptBlock $sb

$job | Wait-Job | Receive-Job

$job | Remove-Job

我得到印$ v1和v2的$空值。我怎样才能让他们在(传递给)的脚本块进行评估,并因此对后台作业?

I get printed empty values of $v1 and $v2. How can I have them evaluated in (passed to) the scriptblock and so to the background job?

推荐答案

一种方法是使用[脚本块] :: Create方法使用的局部变量的expanadable字符串创建脚本块:

One way is to use the [scriptblock]::create method to create the script block from an expanadable string using local variables:

$v1 = "123"
$v2 = "asdf"

$sb = [scriptblock]::Create("Write-Host 'Values are: $v1, $v2'")

$job = Start-Job -ScriptBlock $sb

的另一种方法是设置在InitializationScript变量:

Another method is to set variables in the InitializationScript:

$Init_Script = {
$v1 = "123"
$v2 = "asdf"
}

$sb = {
    Write-Host "Values are: $v1, $v2"
}

$job = Start-Job -InitializationScript $Init_Script -ScriptBlock $sb 

第三个选项是使用-ArgumentList参数:

A third option is to use the -Argumentlist parameter:

$v1 = "123"
$v2 = "asdf"

$sb = {
    Write-Host "Values are: $($args[0]), $($args[1])"
}

$job = Start-Job  -ScriptBlock $sb -ArgumentList $v1,$v2

这篇关于PowerShell的 - 如何美元的启动工作一个脚本块p $ P-评估变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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