PowerShell: Path/Filename Operations

By Xah Lee. Date: . Last updated: .

Check folder/file existence

Use test-path to check if a file/folder exist. It returns True or False.

# check if file/folder exist
test-path c:/Users/xah/web
# check if exist and is folder
test-path c:/Users/xah/web -PathType container
# check if exist and is file
test-path c:/Users/xah/web -PathType leaf

get dir path, file name, file extension

Split-Path -Parent path
return the fullpath of parent dir
Split-Path -Extension path
return the file extension. e.g. ".jpg"
Split-Path -Leaf path
return just the file name. e.g. "cat.jpg"
Split-Path -LeafBase path
return the file name sans extension.
$x = c:/Users/xah/web/xahlee_info/powershell/powershell_path.html

Split-Path -Parent $x
# c:\Users\xah\web\xahlee_info\powershell

Split-Path -extension $x
# .html

Split-Path -leaf $x
# powershell_path.html

Split-Path -leafbase $x
# powershell_path

Split-Path -Qualifier $x
# c:

Split-Path -NoQualifier $x
# /Users/xah/web/xahlee_info/powershell/powershell_path.html

Join Path

This is useful in scripting. It frees you from worrying if the dir path ends in a slash.

join-path "a" "b"
# a\b

join-path "a/" "b"
# a\b

join-path "a" "/b"
# a\b

# duplicate separater
join-path "a/" "/b"
# a\b

# repeated separater are not removed
join-path "a/" "//b"
# a\\b

# drive path
join-path "c:" "b"
# c:\b

join-path "c:/" "/b"
# c:\b

save and restore current dir

These are useful in interactive use as well as in script.

Save current dir to a stack. (alias pushd)
Restore (pop) dir from stack. (alias popd)

PowerShell Path


Practical How-To

list files

list dirs

on dir

on file

Windows config

zip tar


PowerShell in Depth

Programing PowerShell

Value Types





Data Structure

Loop and Iteration



Profile and Script

Script Examples