首页 > 解决方案 > PowerShell 从脚本运行脚本:如果调用失败,则调用者失败

问题描述

我有./main.ps1那个调用./worker1.ps1worker2.ps1参数,来自 main.ps1 的行:

# other stuff in main script
$args = @()
$args += ("-PARAM1", "$VAR1")
$args += ("-PARAM2", "$VAR2")
$worker1 = "./workers/worker1.ps1"
Invoke-Expression "$worker1 $args" -ErrorAction Stop
# other stuff in main script
$worker2 = "./workers/worker2.ps1"
Invoke-Expression "$worker2 $args" -ErrorAction Stop

如果worker1.ps1失败它有exit 1行,
问题是即使worker1.ps1失败worker2.ps1被调用main.ps1

一旦其中一个调用失败,我怎么能避免这种情况并使主脚本失败?

标签: powershell

解决方案


把它们放在一起:

# other stuff in main script

# Define the arguments as a *hashtable*.
$htArgs = @{
  PARAM1 = $VAR1
  PARAM2 = $VAR2
}

foreach ($worker in './workers/worker1.ps1', './workers/worker2.ps1') {
  & $worker @htArgs # Note the @ sigil for splatting
  if ($LASTEXITCODE) { Throw "$worker signaled failure via exit code $LASTEXITCODE" } 
}

推荐阅读