How do I use Join-Path to combine more than two strings into a file path?


Michael A

If I want to combine two strings into a file path, I use join-path like this:

$path = Join-Path C: "Program Files"
Write-Host $path

That prints "C:\Program Files". If I want to do this for more than two strings though:

$path = Join-Path C: "Program Files" "Microsoft Office"
Write-Host $path

PowerShell throws an error:

Join-Path : A positional parameter cannot be found that accepts argument 'Microsoft Office'.
At D:\users\ma\my_script.ps1:1 char:18
+ $path = join-path <<<< C: "Program Files" "Microsoft Office"
+ CategoryInfo : InvalidArgument: :)) [Join-Path], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell
I tried using a string array:

[string[]] $pieces = "C:", "Program Files", "Microsoft Office"
$path = Join-Path $pieces
Write-Host $path

But PowerShell prompts me to enter the childpath (since I didn't specify the -childpath argument), e.g. "somepath", and then creates three files paths,

Program Files\somepath
Microsoft Office\somepath

which isn't right either.

Continue reading...