Reputation: 203
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?
Upvotes: 1
Views: 671
Reputation: 8355
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/
Upvotes: 1