Error Handing in Powershell pipe

3.6k views Asked by At

How can I catch (suppress) an error within a powershell expression?

I am trying to use get-ChildItem to iterate over the files in a directory and extract some information.

get-ChildItem "c:\test\" -Recurse  | % { $_.Name + " ==> " + (try{(([xml] (Get-Content $_.FullName)).DocumentElement.TagName)} catch{"not xml"})  }

I know I could rewrite this not to use the pipe, and catch the error that way, but is it possible make this a one liner?

The above returns "try : The term 'try' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."

1

There are 1 answers

0
briantist On BEST ANSWER

If the error happens during Get-Content, then call it with -ErrorAction Ignore or -ErrorAction SilentlyContinue. If it happens while accessing the properties of the result of Get-Content, then instead of using dot notation, use Select-Object so you can use -ErrorAction on each of those:

get-ChildItem "c:\test\" -Recurse  | % { $_.Name + " ==> " + ((([xml] (Get-Content $_.FullName -ea Ignore)) | Select-Object -ExpandProperty DocumentElement -ea Ignore | Select-Object -ExpandProperty TagName -ea Ignore))  }

You could also use a trap statement somewhere outside of this one-liner, not sure if that counts as a one-liner still.

My recommendation is to not get hung up on something being a one-liner though. Note that pipelines don't need to be one-liners. % is ForEach-Object and the scriptblock you are passing to it can be multiple lines, complete with try/catch, if statements, etc.