Here I will explain two ways I’ve found to concatenate two variables to a path.
I have at multiple occasions had the need to use two variables to form a single path based on input from the command line.
This is an example on how to change location using two variables. This doesn’t work.
$Drive = "D:" $Directory = "Directory" Set-Location $Drive\$Directory
The reason this doesn’t work is that Set-Location accepts $Drive as the entire path and considers $Directory to be a new command.
There are two ways to solve this.
The first was is to create a third variable containing the first two.
$Drive = "D:" $Directory = "Directory" $Path = $Drive + "\" + $Directory Set-Location $Path
This changes the current directory to D:\Directory.
The other way to do this is to use the cmdlet Join-Path.
$Drive = "D:" $Directory = "Directory" Set-Location (Join-Path -Path $Drive -ChildPath $Directory)
The psprovider File System adds the required delimiter “\” and concatenates the two variables to D:\Directory.
In this example I’m using parenthesis to be able to put it in only one line. Powershell looks at the command and resolve the contents of the parenthesis first and then runs the rest of the command.
I hope this will help some of you. I had some major issues with paths and variables before I learned these methods.