gpt4 book ai didi

powershell - 对Foreach对象的错误处理

转载 作者:行者123 更新时间:2023-12-03 07:53:48 25 4
gpt4 key购买 nike

我想做类似的事情:

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应该收到错误并显示“Do n't do it”。但这不是...发生了什么事?

最佳答案

您可以结合使用-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/

关于powershell - 对Foreach对象的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39531060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com