0

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.

1
  • 1
    How are you currently consuming the error? Show us your code Commented Jul 14, 2021 at 9:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I reused the idea you had. Instead of a trap I found out, that the ErrorRecord (from an Event) also has the information at errorRecord.InvocationInfo.PositionMessage since I forward all Write-* to Microsoft.Extension.Logging
Great, glad that was helpful for you Phil! Appreciate your feedback and for accepting the answer, interesting to hear how it applies to your particular solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.