PoshBytes: Your .NET Path Toolkit for PowerShell
A fast paced walkthrough of the most useful System.IO.Path methods in PowerShell with practical demos and humor. Learn how to extract filenames, change extensions, combine paths, and manage temporary files.
This post is a companion for the video embedded below. Scroll down to see the code from the video.
Getting the File Name
Extract WITHOUT extension
[System.IO.Path]::GetFileName('C:\Reports\yearly.xlsx')
[IO.Path]::GetFileNameWithoutExtension('C:\Data\Q4.xlsx')
Changing File Extensions
Remove extension entirely
[IO.Path]::ChangeExtension('C:\Data\yearly.xlsx', '.bak')
[IO.Path]::ChangeExtension('C:\Data\yearly.xlsx', $null)
Getting Just the Extension
What if the file has MULTIPLE extensions?
[IO.Path]::GetExtension('C:\Data\yearly.xlsx')
[IO.Path]::GetExtension('C:\Data\archive.tar.gz')
Getting the Directory Name
Nested paths behave just fine
[IO.Path]::GetDirectoryName('C:\Data\yearly.xlsx')
[IO.Path]::GetDirectoryName('C:\One\Two\Three\four.txt')
Combining Paths
Combine several parts
[IO.Path]::Combine('C:\Data', 'Reports')
[IO.Path]::Combine('C:\Data', 'Reports', 'Q4', '10k.txt')
Getting the Root Path
[IO.Path]::GetPathRoot('C:\Data\yearly.xlsx')
Checking for Invalid Characters
Check whether a string contains any invalid file name characters
[IO.Path]::GetInvalidFileNameChars() -join('')
[IO.Path]::GetInvalidPathChars() -join('')
('file?name.txt').ToCharArray() | Where-Object { $_ -in
[IO.Path]::GetInvalidFileNameChars() } |
Foreach-Object{
Write-Host "Invalid character found $_" -Fore red
}
Getting a Random Temp File
Get a random file name (no folder implied)
[IO.Path]::GetTempFileName()
[IO.Path]::GetRandomFileName()
Wrap Up
• Extract file names and extensions
• Change or remove extensions
• Get directory, root, and temp paths
• Combine paths safely
• Identify invalid characters
• Generate temp/random file names