Search code examples
powershellpowershell-4.0

Get-ChildItem -SilentlyContinue throws AccessDenied


Code:

$cPstFiles = Get-ChildItem -Path $env:USERPROFILE -File -Force `
    -Recurse -Include "*.pst" -ErrorAction "SilentlyContinue"

Exception:

Get-ChildItem : Access is denied
At test.ps1:172 char:22
+         $cPstFiles = Get-ChildItem -Path $env:USERPROFILE -File -Force `
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetChildItemCommand

Context: PowerShell v4.0/.NET 4.5.2/Windows 7.

How is this even possible? And how can I make SilentlyContinue do what it's supposed to do?

It's probably worth mentioning that the script doesn't always fail. It fails on some machines but works just fine on others even though on all of them Windows is deployed using the same image.


Solution

  • $ErrorActionPreference = “silentlycontinue”
    $Extension = "*pst"
        $TargetFolder = "$env:userprofile"
        Get-Childitem $TargetFolder -Include $Extension -Recurse