Home QuickTipps Bug Test-Path Ignores Some Files
 

Test-Path Ignores Some Files

Test-Path can check whether a file or folder exists, but it won’t recognize some system files such as pagefile.sys or hiberfil.sys.

The next line returns $false although the file most definitely exists. It is just hidden:

Test-Path c:\pagefile.sys

To check for any file, regardless of attributes and system status, here is a workaround that uses a .NET function to list all files in a folder:

function Test-PathEx
{
    param($Path)

    if (Test-Path $Path)
    {
        $true
    }
    else
    {
        $parent = Split-Path $Path
        [System.IO.Directory]::EnumerateFiles($Parent) -contains $Path
    }
}