Working with Paths in PowerShell

Image Description

Daily PowerShell #59

Daily PowerShell Basics

December 15, 2021

quote Discuss this Article

In this post, we’ll look at numerous ways to work with paths. All of these commands work cross-platform.

Join Paths

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")

Split Paths

You can split paths to get the parent or leaf path.

Parent Path

Split-Path "C:\users\adamr\desktop"
# C:\users\adamr

Leaf Path

Split-Path "C:\users\adamr\desktop" -Leaf
# desktop

Exists

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')

File Extensions

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

Known Paths

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:\

Temporary Files

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\

System Path Information

Use [IO.Path] to get information about the current system paths.

[IO.Path]::DirectorySeparatorChar
# \
[IO.Path]::PathSeparator
# ;
[IO.Path]::AltDirectorySeparatorChar
# /
[IO.Path]::InvalidPathChars         
<#
|

§

#>