查看: 1773|回复: 0

[.NET源码] Powershell如何在Start-Job的Scriptblock里传参?

发表于 2018-3-5 08:00:00

如何在Start-Job的Scriptblock里传参?

方法1:

利用本地变量,从一个可扩展的字符串,使用[scriptblock]::create方法创建脚本块:

  1. $v1 = "123"
  2. $v2 = "asdf"
  3. $sb = [scriptblock]::Create("Write-Host 'Values are: $v1, $v2'")
  4. $job = Start-Job -ScriptBlock $sb
  5. # 另一种写法
  6. [scriptblock]$sb =
  7. {
  8. Write-Host "Values are: $v1, $v2"
  9. }
复制代码



方法2:

在InitializationScript中设置变量

  1. $Init_Script = {
  2. $v1 = "123"
  3. $v2 = "asdf"
  4. }
  5. $sb = {
  6. Write-Host "Values are: $v1, $v2"
  7. }
  8. $job = Start-Job -InitializationScript $Init_Script -ScriptBlock $sb
复制代码



方法3:

使用-Argumentlist参数

  1. $v1 = "123"
  2. $v2 = "asdf"
  3. $sb = {
  4. Write-Host "Values are: $($args[0]), $($args[1])"
  5. }
  6. $job = Start-Job -ScriptBlock $sb -ArgumentList $v1,$v2
复制代码




回复

使用道具 举报