PowerShell for Windows Admins

Oct 22 2018   10:45AM GMT

Managing errors

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


If you try to do a directory listing through C:\Windows\system32 you’ll get some access denied errors. I’m going to show you how to do this while managing errors that arise. The code will also highlight a few of the PowerShell error handling techniques.


$epath2 = $null

Get-ChildItem -Path C:\Windows\System32 -Recurse -Force -Directory -ErrorVariable epath2 |
foreach {
if ($?) {
Out-File -InputObject $_.FullName -FilePath c:\test\paths.txt -Append

if ($epath2) {
$epath2 |
foreach {
($_.Exception -split “‘”)[1] | Out-File -FilePath c:\test\errors.txt -Append


Set $epath2 to $null to clear any data.


Use -ErrorVariable epath2  to define the variable into which errors are directed.


Get-ChildItem will recurse through the folder structure – use –Directory to ignore files.


In the foreach statement check $? which holds True or False depending on if last statement succeeded. Append the full path to the folder to the paths.txt file.


If $epath2 has a value then iterate over the values splitting out the folder paths from the error statement.  Write to errors.txt

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: