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:/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 dir part of path
Split-Path -Leaf path
- return just the file name.
e.g.
"cat.jpg"
Split-Path -Extension path
- return the file extension.
e.g.
".jpg"
Split-Path -LeafBase path
- return the file name sans extension.
$x = "c:/Users/xah/web/xahlee_info/powershell/powershell_path.html" # dir part Split-Path -Parent $x # c:\Users\xah\web\xahlee_info\powershell # file name part Split-Path -leaf $x # powershell_path.html # file core name part Split-Path -leafbase $x # powershell_path Split-Path -extension $x # .html 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
)