Categories

Path cmdlets: 4 Joining paths

 

During our processing we get a path and a file we need to join together to produce the full path to a file.

$path = "c:\scripts"
$file = "test2.csv"

One way that I saw a lot in this years Scripting Games is to use string concatenation

PS> $path + "\" + $file
c:\scripts\test2.csv

We could use string substitution which is a bit neater

PS> "$path\$file"
c:\scripts\test2.csv

Choice number 3 is to use Join-Path

PS> Join-Path -Path $path -ChildPath $file
c:\scripts\test2.csv

We can also use it to resolve paths

PS> Join-Path -Path $path -ChildPath "*.csv" -Resolve
C:\scripts\auto.csv
C:\scripts\chapt4.csv
C:\scripts\iehistory.csv
C:\scripts\Services.csv
C:\scripts\test.csv
C:\scripts\test2.csv
C:\scripts\tp.csv

We can then do things like this

PS> Join-Path -Path $path -ChildPath "*.csv" -Resolve |
>> foreach {Get-ItemProperty -Path $_ -Name Length}
>>


PSPath       : Microsoft.PowerShell.Core\FileSystem::C:\scripts\auto.csv
PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\scripts
PSChildName  : auto.csv
PSDrive      : C
PSProvider   : Microsoft.PowerShell.Core\FileSystem
Length       : 18582

etc

Leave a Reply