Powershell - 如何为 Start-Job 预先评估脚本块中的变量 [英] Powershell - how to pre-evaluate variables in a scriptblock for Start-Job

查看:31
本文介绍了Powershell - 如何为 Start-Job 预先评估脚本块中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Powershell 中使用后台作业.

I want to use background jobs in Powershell.

如何在 ScriptBlock 定义时评估变量?

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?

推荐答案

一种方法是使用 [scriptblock]::create 方法使用局部变量从可扩展字符串创建脚本块:

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 - 如何为 Start-Job 预先评估脚本块中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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