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.

Push-Location
Save current dir to a stack. (alias pushd)
Pop-Location
Restore (pop) dir from stack. (alias popd)

PowerShell Path

PowerShell

Practical How-To

PowerShell in Depth

Programing PowerShell

String

Variable

Boolean

Conditional

Data Structure

Loop and Iteration

Input/Output

Function

Profile and Script

Script Examples