Ironman Software Forums
Continue the conversion on the Ironman Software forums. Chat with over 1000 users about PowerShell, PowerShell Universal, and PowerShell Pro Tools.
In this post, we’ll look at numerous ways to work with paths. All of these commands work cross-platform.
There are a couple ways to join paths.
Join-Path
You can use Join-Path
to join directories or files and directories.
Join-Path 'C:\Users' 'adamr'
Path.Combine
You can use [IO.Path]::Combine
to combine more than two path segments.
[IO.Path]::Combine("C:", "Users", "adamr", "Desktop")
You can split paths to get the parent or leaf path.
Split-Path "C:\users\adamr\desktop"
# C:\users\adamr
Split-Path "C:\users\adamr\desktop" -Leaf
# desktop
Check if a file or directory exists.
Test-Path
Test-Path C:\users\adamr
IO.Directory
[IO.Directory]::Exists('C:\users\adamr')
IO.File
"Note" | Out-File C:\users\adamr\desktop\note.txt
[IO.File]::Exists('C:\users\adamr\desktop\note.txt')
You can use IO.Path
and IO.FileInfo
to get file extensions.
IO.FileInfo
"Note" | Out-File C:\users\adamr\desktop\note.txt
(Get-Item C:\users\adamr\desktop\note.txt).Extension
# .txt
IO.Path
[IO.Path]::GetExtension('C:\users\adamr\desktop\note.txt')
# .txt
You can use the [Environment]
class to get known paths.
[Environment]::GetFolderPath('ProgramFiles')
# C:\Program Files
[Environment]::GetFolderPath('ApplicationData')
# C:\Users\adamr\AppData\Roaming
$CommonAdminTools = [Environment+SpecialFolder]::CommonAdminTools
[Environment]::GetFolderPath($CommonAdminTools)
# C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools
[Enum]::GetValues([Environment+SpecialFolder])
# List of possible values
You can also use environment variables.
$Env:AppData
# C:\Users\adamr\AppData\Roaming
Get-ChildItem Env:\
You can use [IO.Path]
to get temporary file names and the temporary directory.
IO.Path
[IO.Path]::GetTempFileName()
# C:\Users\adamr\AppData\Local\Temp\tmpAFD8.tmp
[IO.Path]::GetTempPath()
# C:\Users\adamr\AppData\Local\Temp\
Use [IO.Path]
to get information about the current system paths.
[IO.Path]::DirectorySeparatorChar
# \
[IO.Path]::PathSeparator
# ;
[IO.Path]::AltDirectorySeparatorChar
# /
[IO.Path]::InvalidPathChars
<#
|
☺
☻
♥
♦
♣
♠
►
◄
↕
‼
¶
§
▬
↨
↑
↓
→
∟
↔
▲
▼
#>
Find this useful? Please consider sharing this article. Have a question about PowerShell? Contact us and we'll write a post about it.
Continue the conversion on the Ironman Software forums. Chat with over 1000 users about PowerShell, PowerShell Universal, and PowerShell Pro Tools.
Receive once-a-month updates about Ironman Software. You'll learn about our product updates and blogs related to PowerShell.