I have several powershell scripts that I am running from one powershell scripts.
I am using a try-catch to stop on errors. But that doesn't work with external scripts I'm calling. I cant use dot-source because some of the scripts require the 32 bit version of PowerShell (has to do with QuickBooks API call requiring 32bit)
So I am currently calling it using the full path name so i have something like this:
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]
}
If I am dot-sourcing the scripts it works fine, but external calling it, it does not. Suggestions on how to catch the errors and stop the script?
CodePudding user response:
If you want try-catch to work with executables in PowerShell session, then you must do the following:
- Set
$errorActionPreference = 'stop'
so that all errors are terminating - Redirect error stream elsewhere for the executable call -> 2>$null for example.
$EAPBackup = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
try {
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -file $ScriptDir\QB_API_Open_Sales_Orders_by_Item.ps1 2>$null
} catch {
Write-Warning $error[0]
}
$ErrorActionPreference = $EAPBackup