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."
 
                        
If the error happens during
Get-Content, then call it with-ErrorAction Ignoreor-ErrorAction SilentlyContinue. If it happens while accessing the properties of the result ofGet-Content, then instead of using dot notation, useSelect-Objectso you can use-ErrorActionon each of those:You could also use a
trapstatement 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.
%isForEach-Objectand the scriptblock you are passing to it can be multiple lines, complete withtry/catch,ifstatements, etc.