Concatenating variables in PowerShell

I have defined some powershell variables like below

$Host101 = "10.1.1.101"
$Host102 = "10.1.1.102"
$HDD101 = "DataStoreH101"
$HDD102 = "DataStoreH102"
$SSD101 = "DataStoreS101"
$SSD102 = "DataStoreS102"
My-Command -H $Host101 -Disk $HDD101 -Disk $SSD101

Now, I want to define $Node = "101" and then use the following command

My-Command -H $Host$Node -Disk $HDD$Node -Disk $SSD$Node

As I test Write-Host "$HDD$Node", it doesn't print DataStoreH101. How can I write something like that in powershell?

3

1 Answer

As others have said, you have to also define the $Node variable and its value before you can use it. I will assume you already know this and that was just an oversight left out of the question.

I've used similar PowerShell solutions to concatenate part of a variable's name to set the variable and then later have that fully concatenated variable executed using Invoke-Expression.

PowerShell

$Host101 = "10.1.1.101";
$Host102 = "10.1.1.102";
$HDD101 = "DataStoreH101";
$HDD102 = "DataStoreH102";
$SSD101 = "DataStoreS101";
$SSD102 = "DataStoreS102";
$Node = "101"; ## Set the node number to concatenate to variable name before invoking it
$cmd = "Write-Host `"-H `$Host$Node -Disk `$HDD$Node -Disk `$SSD$Node`" -ForegroundColor Green"
Invoke-Expression -Command $cmd

Script Notes

  • You will need to prefix a backtick [`] character before the first part of the literal variable name that contains the literal $ character in the $cmd value so it is still a literal dollar sign to be invoked and can be expanded to the full concatenated value when invoked.

  • For My-Command I've used Write-Hostso I had to put a backtick prefix before the double quotes within it so at execution time the $cmd variable still contains those for when it is invoked for the string value—be aware of this with whatever command you are using with this solution as well.

  • If possible otherwise with the command you use, you could replace the inner double quotes with single quotes. Then you'd just keep the outer double quotes and not need to escape the inner single quotes with the backtick character.

  • E.g.

    $cmd = "Write-Host '-H `$Host$Node -Disk `$HDD$Node -Disk `$SSD$Node' -ForegroundColor Green"

Output Examples

Running $cmd outputs this

Write-Host "-H $Host101 -Disk $HDD101 -Disk $SSD101" -ForegroundColor Green

Running Invoke-Expression -Command $cmd; outputs this (in green of course)

-H 10.1.1.101 -Disk DataStoreH101 -Disk DataStoreS101

PowerShell ISE output with screen shot annotations

enter image description here

Supporting Resources

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like