Foreach-Object上的错误处理

时间:2016-09-16 12:04:29

标签: powershell error-handling

我想做类似的事情:

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
}

我该怎么做?

编辑: 我目前有这个:

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

假设$ somelongpath是超过260限制的路径,因此get-childitem应该收到错误并打印"不要这样做"。但它没有...发生了什么?

1 个答案:

答案 0 :(得分:1)

您可以使用-ErrorAction-ErrorVariable的组合。似乎以这种方式使用-Recurse只是忽略了带错误的目录,所以我写了一个小的递归函数。

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/