windowspowershellexceptionget-childitemunauthorizedaccessexcepti

Powershell script - gci


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.


Solution

  • 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