Hairy
Hairy

Reputation: 101

Trapping errors in PowerShell not working as expected

I am using a recursive call to Get-Children in order to get the total size of a folder/directory structure. It works fine, but doesn't keep the errors in the ErrorVariable that I use, and from looking at documentation, it simply should? Any ideas?

        [string]$fsoobjexist = Test-Path -Path $Folder
        $err=@() 
        If ($fsoobjexist -eq "True"){
            $err.clear
            if ((Get-Item $Folder) -is [System.IO.DirectoryInfo]){
                $Foldersize = "{0:N2} MB" -f ((Get-ChildItem -LiteralPath $Folder -Force -Recurse | Measure-Object -Property Length -Sum -EV +err -EA Continue  ).Sum / 1MB) 
                $logline = "$Folder,$Foldersize" 
                LogWrite $logline       

                Foreach ($Errors in $err){
                    ErrLogWrite "$($Errors.CategoryInfo.Category) $($Errors.CategoryInfo.Activity) $($Errors.CategoryInfo.Reason) $($Errors.CategoryInfo.TargetName) $($Errors.CategoryInfo.TargetType) $($Errors.Exception.Message)" 
                }
            }
        }

Upvotes: 0

Views: 47

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174555

You've passed +err as an argument to the ErrorVariable parameter of Measure-Object, but it's likely the Get-ChildItem cmdlet that throws the error.

Change it to:

$Foldersize = "{0:N2} MB" -f ((Get-ChildItem -LiteralPath $Folder -Force -Recurse -EV +err -EA Continue | Measure-Object -Property Length -Sum).Sum / 1MB) 

Upvotes: 2

Related Questions