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
.Commands.JoinPathCommand
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,
C:\somepath
Program Files\somepath
Microsoft Office\somepath
which isn't right either.
You can use the .NET Path class:
[IO.Path]::Combine('C:\', 'Foo', 'Bar')