【发布时间】:2021-12-24 06:17:51
【问题描述】:
我有几个 powershell 脚本,我从一个 powershell 脚本运行。
我正在使用 try-catch 来停止错误。但这不适用于我正在调用的外部脚本。我不能使用点源,因为某些脚本需要 32 位版本的 PowerShell(与需要 32 位的 QuickBooks API 调用有关)
所以我目前使用完整路径名来调用它,所以我有这样的东西:
try {
# QB API requires powershell 32 bit: Open Sales Order by Item Report Call
& C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -file $ScriptDir\QB_API_Open_Sales_Orders_by_Item.ps1
# QB API requires powershell 32 bit: Inventory List Call
& C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -file $ScriptDir\QB_API_Inventory_List.ps1
# x64bit powershell: Convert QB_API Sales and Inventory Fiels from XML to CSV using XSLT
& C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -file $ScriptDir\transform_xml.ps1
# x64bit powershell: run vendor vs sales file to get final output
& C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -file $ScriptDir\Create_Sales_order_MPN_using_join.ps1
}
catch
{
Write-Warning $Error[0]
}
如果我对脚本进行点源,它可以正常工作,但外部调用它,它就不行。关于如何捕获错误并停止脚本的建议?
【问题讨论】:
-
@AdminOfThings 为什么我不想在错误发生时自动调用 write-error?执行 2>$null 是否允许 catch 部分显示错误?
-
您可以评估外部调用的返回码。
-
如果脚本设置了
$ErrorActionPreference = 'Stop',那么$lastexitcode将是调用shell 中出错时的非零值。 -
如果您希望
try-catch在 PowerShell 会话中使用可执行文件,那么您必须执行以下操作:1) 设置$errorActionPreference = 'stop'以便所有错误都终止。 2) 将可执行调用的错误流重定向到别处 ->2>$null例如。然后您可以根据需要选择调用Write-Error,但无论如何,$error[0]将包含您的异常。 -
如果您将 cmets 放入答案中,则将其标记为正确。感谢您的帮助。将 erroractionpreference 设置为 stop 似乎已经成功了
标签: powershell try-catch dot-source