Reputation: 135
I have a powershell script running in a c# service (System.Management.Automation). Sometimes seldom I get the following error:
Unable to cast object of type 'System.Double' to type 'System.String'.
Is is somehow possible to include the variable name, line number or anything that could help me find the error location? E.g. code that runs in a powershell terminal shows me the corresponding line.
Upvotes: 0
Views: 392
Reputation: 512
It's worth thinking through your error handling and error logging approach to avoid issues like this. Consider whether you want your error to be terminating or non-terminating, and whether you want to suppress or log the error.
Much has already been written on SO on detecting and handling script errors, and there is also ample MS documentation on Trap and Try-Catch-Finally, so I don't want to go over that ground.
Depending on where the script runs from and with what credentials, one trick would be to record errors to a logfile you could check when these errors happen:
# Create C:\Temp directory if it doesn't exist
New-Item "C:\Temp" -Force -ItemType Directory | Out-Null
# Simple trap to catch all errors
trap {
# This is a single-line output more suitable for on-screen error messages
Write-Output "Error encountered: $_ $($_.InvocationInfo.PositionMessage.Split("`n")[0])"
# This is a multi-line output to make it easier to find the error location in a file
Add-Content -LiteralPath "C:\Temp\logfiletest.txt" -Value $_,$_.InvocationInfo.PositionMessage
return
}
# Div/0 triggers the trap to test behaviour
1/0
The trap alone (or something like it) should catch the error you're hitting. Though in practice (not knowing how often you run it or how many errors you generate) you'd want to be wary that you don't inadvertently start generating excessively large logfiles on C: - you could avoid this by selecting a lower-risk drive/location and putting a dynamic date into the filename.
Upvotes: 1