🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell File Paths

A file path is text that gives the location of a file. PowerShell has commands that build paths and split them into parts, so you do not have to type separators by hand.

Join-Path builds a path

Give Join-Path a folder and a file name. It puts the right separator between them.

$path = Join-Path -Path "notes" -ChildPath "a.txt"
$path

Split-Path gives the parts

The -Leaf part is the file name. The -Parent part is the folder.

$path = Join-Path -Path "notes" -ChildPath "a.txt"
Split-Path -Path $path -Leaf
Split-Path -Path $path -Parent

Test-Path checks existence

Create the file first, then test it. A missing file gives False.

Set-Content -Path "a.txt" -Value "apple"
Test-Path -Path "a.txt"
Test-Path -Path "missing.txt"

Example

$path = Join-Path -Path "." -ChildPath "log.txt"
Set-Content -Path $path -Value "ready"
Test-Path -Path $path
Split-Path -Path $path -Leaf

Key points

  • File path: text that gives the location of a file.
  • Join-Path joins a folder and a file name into one path.
  • Split-Path with -Leaf gives the file name at the end of a path.
  • Split-Path with -Parent gives the folder part of a path.
  • Test-Path checks whether a path exists and gives True or False.

In this example, Join-Path builds the path to log.txt in the current folder. Set-Content creates the file at that path. Test-Path then confirms the file exists, and Split-Path gives back just the file name.

Note

a path is only text until a command uses it, so a joined path can name a file that does not exist yet.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Split-Path -Path "notes/a.txt" -Leaf give back?