After sending a request to powerGateServer the $error variable is empty when it is read within a .psm1 file.
Issue
After sending a request to powerGateServer(PGS) and an error is returned by PGS the $error variable is empty when it is read within a .psm1 file.
Cause
PowerShell modules define a separate $error variable within the modules script scope. In most situations the global $error variable will be used.
This can be verified like this:
- Create a module pg_test_error_not_set.psm1 with the following contents
function TestErrorVariable {
try {
throw "nope!"
}
catch {
Write-Host -Object ("Errors - Global: {0}; Module: {1}" -f $Global:Error.Count, $Script:Error.Count) -ForegroundColor Yellow
}
}
- In a .ps1 file or any PowerShell console load the module and call the function TestErrorVariable
Result: Errors - Global: 1; Module: 0 will be displayed
Solution
As PowerShell will set the global $error variable in most situations you need to use the global scope modifier if you want to read the $error variable within a module file. For example:
if(-not $?){
$message = 'Status: {0}; Message: {1}' -f $Global:Error[0].Exception.StatusCode, $Global:Error[0].Exception.Message
}