首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对Foreach-Object的错误处理

对Foreach-Object的错误处理
EN

Stack Overflow用户
提问于 2016-09-16 20:04:29
回答 1查看 468关注 0票数 1

我想做一些类似的事情:

代码语言:javascript
复制
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
}

我该怎么做呢?

编辑:我现在有这个:

代码语言:javascript
复制
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应该收到一个错误并打印“do‘t do it”。但它不是..。这是怎么回事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-16 20:40:00

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

代码语言:javascript
复制
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/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39531060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档