简体   繁体   中英

Error handling on a Foreach-Object

I want to do something like:

Get-ChildItem "somepath" | where {$_.PSIsContainer} | ForEach-Object{
    #do something if Get-ChildItem didn't receive an error
    #else do something else if did get an error
}

How do I go about this?

EDIT: I currently have this:

Get-ChildItem $somelongpath -Recurse -ErrorVariable MyError -ErrorAction Stop  | where {$_.PSIsContainer} | ForEach-Object{
     if($MyError){
        Write-Host "Don't do it"
     } else {
        Write-Host "Yay!"
     }
}

Say that $somelongpath is a path that exceeds the 260 limit and therefore get-childitem should receive an error and print "Don't do it". But it doesn't... What is happening?

You can use a combination of -ErrorAction and -ErrorVariable . It seems that using -Recurse in this way just ignores the directory with the error so I wrote a little recursive function instead.

gci -Attributes Directory | Foreach {
    foo $_.FullName
}

function foo
{
    Param ([string] $currentPath)

    Write-Host "Getting subdirectories of" $currentPath

    $result = gci $currentPath -Attributes Directory -ErrorVariable HasError -ErrorAction SilentlyContinue

    if($HasError) { 
        Write-Host "error" $HasError
    }
    else {
        Write-Host "ok"    
    }

    if($result) {
        $result | Foreach {
            foo $_.FullName
        }
    }
}

https://blogs.technet.microsoft.com/heyscriptingguy/2014/07/09/handling-errors-the-powershell-way/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM