PowerShell: Path Filename Functions
Check Folder / File Existence
test-path
-
return true if file/folder exist. [PowerShell: True, False (boolean)]
# check if file/folder exist test-path c:/ProgramData/ # True
# check if exist and is folder test-path c:/ProgramData/ -PathType container # True
# check if exist and is file test-path c:/ProgramData/ -PathType leaf # False
Check if drive e exist
# check if drive e exist (Test-Path -Path "e:/")
# check if a external usb drive is mounted $destDriveLetter = foreach ($x in @("e", "f")) { if (Test-Path -Path ($x + ":/")) { return $x } } if (-not $destDriveLetter) { throw "drive e or f no exist" } # see also Get-Volume
Get Dir Path, File Name, File Extension
Split-Path -Parent path
-
return the dir part of path
# dir part (Split-Path -Parent "C:/a/b/ff.jpg") # C:\a\b
Split-Path -Leaf path
-
return just the file name.
# file name (Split-Path -Leaf "C:/a/b/ff.jpg") # ff.jpg
Split-Path -Extension path
-
return the file extension.
(Split-Path -Extension "C:/a/b/ff.jpg") # .jpg
Split-Path -LeafBase path
-
return the file name sans extension.
# file core name (Split-Path -LeafBase "C:/a/b/ff.jpg") # ff
Split-Path -NoQualifier path
-
remove driver letter.
(Split-Path -NoQualifier "C:/a/b/ff.jpg") # /a/b/ff.jpg
Split-Path -Qualifier path
-
get driver letter.
(Split-Path -Qualifier "C:/a/b/ff.jpg") # C:
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
(aliaspushd
)-
Save current dir to a stack.
Pop-Location
(aliaspopd
)-
Restore (pop) dir from stack.