我想做一些类似的事情:
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‘t do it”。但它不是..。这是怎么回事?
发布于 2016-09-16 20:40:00
您可以组合使用-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/
https://stackoverflow.com/questions/39531060
复制相似问题