Search code examples
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.

    • That is, with 4 input paths, as in your example, you'll get 4 Boolean output values.

    • Coercing an array with two ore more elements - irrespective of the type of its elements - to a single Boolean, such as in the context of an if statement's conditional, always yields $true; e.g.:

      [bool] @($false, $false) # -> !! $true
      
      • (By contrast, a single-element array is coerced the same way as its single element itself, so that [bool] @($false) is effectively the same as [bool] $false and therefore $false).

      • See the conceptual about_Booleans help topic for more information.


    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.)