0

I'm trying to divide output into two files with following script:

try {
    gci C:\Windows\System32 -r -Force | % {
        if (!$_.PsIsContainer) {
            $_.FullName;
            $file = $_.FullName
        }
    } > paths.txt
} catch [System.UnauthorizedAccessException] {
    $file > errors.txt
}

I'm aware that you can't catch non-terminating scripts with catch [System.UnauthorizedAccessException], but I don't want to use -ErrorAction Stop with catch [System.Management.Automation.ActionPreferenceStopException] either (like here), because I won't get all file paths.

2
  • 2
    As a side issue, try to avoid using aliases (gci, %) in scripts as it can make them harder to maintain. Also, if you are using PowerShell v3 or later you don't need to use $_.PsisContainer, but can use the -Directory/-File switches for Get-Childitem: FileSystem Provider Commented Oct 22, 2018 at 9:16
  • @boxdog Thanks for advice! Commented Oct 24, 2018 at 8:51

1 Answer 1

0

This worked for me

$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
  }
}

catch the errors in the -ErrorAction variable and send to errors.txt as a second pass. There may be other errors than access denied but you'll know which folders were showing problems

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

Comments

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.