Home > Software engineering >  Does Test-Path accept Relative Paths?
Does Test-Path accept Relative Paths?

Time:11-11

Relative paths seem to work when using Test-Path cmdlet, but I can't find any official documentation supporting this.

If they are supported:

  • do they work in Powershell 2.0?
  • which path are they relative to?
    • Script path? Execution path? somewhere else?
  • how does one change the root relative path? (e.g. script path to something else)

My limited testing suggests that it's relative to the script path (the folder in which the script resides). Is this always the case? If so, then I could reliably use Join-Path to alter that path.

CodePudding user response:

Yes, Test-Path accepts relative paths.

As is typical, a relative path is interpreted as relative to the session's current location, as reflected in the automatic $PWD variable and in the output from Get-Location.

The current location can also be represented as .

Note that while locations are typically file-system directories, PowerShell's provider model allows for other data stores to be presented in a file-system-like manner as well, such as the registry on Windows, for instance (drives HKCU: and HKLM:)

Therefore, the following commands are equivalent:

# Test if an item named 'foo' exists in the current location.
# If the current location is a *file-system* location, this
# could be either a file or a directory. 
# Add:
#  -PathType Container to test only for a directory (container item)
#  -PathType Leaf to test only for a file (leaf item)
Test-Path foo
Test-Path .\foo
Test-Path (Join-Path $PWD foo)

As Lee Dailey notes, in scripts it is better to use full paths instead - unless you carefully control the current location beforehand, but note that changing the current location (with Set-Location or Push-Location) changes it session-wide, so it's best to restore the previous location before exiting your script, which you can do via paired Push-Location / Pop-Location calls.


If, by contrast, you need to test a path relative to your script's location, use the automatic $PSScriptRoot variable, as Santiago Squarzon suggests:

# Test if a file or directory named 'foo' exists in the directory
# in which the enclosing script is located.
Test-Path (Join-Path $PSScriptRoot foo)
  • Related