powershellpathbooleanfile-exists

Test-Path -Path behaviour with array of paths


I'm trying to check if multiple files/folders exist. The Test-Path parameter -Path accepts a [string[]] array. Please see example code:

$arr = @(
    "C:\a\fake\path\test1.txt",
    "C:\another\fake\path\test2.txt",
    "C:\not\a\path\test3.txt",
    "Z:\not\a\path"
)
if (Test-Path -Path $arr) {
    $true
} else {
    $false
}

Output: $true

None of the paths in $arr are valid. They do not exist (I don't have a Z: drive) -- what is happening here?


Solution

  • Building on the helpful comments:

    Test-Path does support passing an array of paths (both by argument and via the pipeline, but it outputs a Boolean value ($true or $false) indicating the existence of a path for each input path.


    If you want to know if at least one of the input paths doesn't exist, use the -contains operator:

    if ((Test-Path -Path $arr) -contains $false) {
      "At least one of the input paths doesn't exist."
    }
    

    (Conversely, -contains $true tells if you at least one path exists.)