PowerShell

PowerShell: Split-Path Examples

The cmdlet Split-Path can be useful to split volumes, folder and file path names. In this blog posts I will give you some examples you can build on. Have fun reading the code samples to learn more about the power of Split-Path.

Code Samples

Please refer to the following code sample and its comments.

# Split Paths
# Show file path
Split-Path $home\documents\test.txt -Parent               
# Show last element
Split-Path $home\documents\text.txt -Leaf                  
Split-Path $home\documents -Leaf      
# Show Drive Letter                 
Split-Path $home\documents\text.txt -Qualifier
# Path without Drive Letter         
Split-Path $home\documents\text.txt -NoQualifier   
# Resolve Name (Show full path) 
Split-Path $home\documents -Resolve                         

# Show Sub-Folder (dir3)
Split-Path (Split-Path c:\dir1\dir2\dir3\file.txt -Parent) -Leaf    
# Show Sub-Folder (dir2)
Split-Path c:\dir1\dir2\dir3\file.txt -Parent |                 
# Show Sub-Folder (dir2)
Split-Path c:\dir1\dir2\dir3\file.txt -Parent | Split-Path -Leaf                             
# Or ...
('c:\dir1\dir2\dir3\file.txt' -split '\\')[2]
# Displays all word documents file names
Set-Location C:\
Split-Path -Path .\temp\*.docx -Resolve -Leaf         
# Is this an absolute path ?
Split-Path $home\documents\text.txt -IsAbsolute         
Split-Path .\Windows -IsAbsolute                        

# Combination 😉
(Split-Path C:\Windows\system32) + '\' 
+ (Split-Path $home\documents\test.txt -Leaf)

Hope this article was helpful!

Categories: PowerShell

Tagged as: ,

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.