powershell - PowerShell 从脚本运行脚本:如果调用失败,则调用者失败
问题描述
我有./main.ps1
那个调用./worker1.ps1
和worker2.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
一旦其中一个调用失败,我怎么能避免这种情况并使主脚本失败?
解决方案
如果您的脚本使用
exit
非零参数来表示失败,请查询自动$LASTEXITCODE
变量以推断失败。
把它们放在一起:
# 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" }
}
推荐阅读
- clipboard - API 在 monaco-editor 中获取 html 格式的内容?
- python - 使用 Tee-Object 将 python 脚本的结果输出到终端和文件
- javascript - 如何在 ejs 文件、nodeJS 应用程序中包含 JS 脚本?
- video - 视频文件在 Chrome 而不是 Safari 中找到/工作,无论 HTML 标签如何
- hibernate - 休眠删除父级
- java - 使用 Room 将二进制文件的链接与元数据一起存储是一种好习惯吗?
- r - 在函数中修改变量的内存有效方法
- javascript - 如何循环获取数组Javascript中对象的值?
- asp.net-mvc - 想从服务器路径中选择图像并将其转换为二进制形式
- c# - 任务列表没有给我我的期望