I'm not able to force my function to skip a folder that doesn't exist and keeps checking others.
I created a small function that measure folders. It does work but if the path of the folder is wrong the whole function stops, even though the rest is fine.
I tried few things with try and catch, $ErrorActionPreference and errorAction but with no avail. It seems either I put those in a wrong place or the error is caused by the ValidateScriptParameter which stops the loop if the path does not exist.
I'd be glad for any suggestions how to best resolve this :) If I see my code working as I intended it would help me a lot with understanding error handling in PS.
function get-folder {
[cmdletbinding()]
param (
[ValidateScript({
if( -not ($_ | Test-Path) ){
throw "PATH DOESN'T EXIST!" }
return $true
})]
[parameter(valueFromPipeline=$true)]
[string[]]$path)
begin {}
process
{
foreach ($p in $path){
try {
Get-ChildItem -path $p -Recurse -File | Measure-Object -Property Length
-Sum
}
catch
{Write-Warning "The path: $p doesn't exist"
}
}
}
end{}
}
The error msg I'm getting when one of the paths is not correct:
PS C:\powershell\Moje_nowe> get-folder "C:\powershell",
"c:\!dump","c:\hostt"
get-folder : Cannot validate argument on parameter 'path'. PATH DOESN'T
EXIST!
At line:1 char:12
+ get-folder "C:\powershell", "c:\!dump","c:\hostt"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [get-folder],
ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,get-folder
try {get-folder -path c:\ziggity} catch {Write-Warning 'Something went WRONG!'}<<< will give you this >>>WARNING: Something went WRONG!<<< without the error text.get-folder -path c:\FolderThatAintThere. when i use your code for the function and use it in the way shown in my previous reply, it suppresses the error message and only shows thecatchblock output.