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 $SSD101Now, I want to define $Node = "101" and then use the following command
My-Command -H $Host$Node -Disk $HDD$Node -Disk $SSD$NodeAs I test Write-Host "$HDD$Node", it doesn't print DataStoreH101. How can I write something like that in powershell?
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 $cmdScript 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$cmdvalue so it is still a literal dollar sign to be invoked and can be expanded to the full concatenated value when invoked.For
My-CommandI've usedWrite-Hostso I had to put a backtick prefix before the double quotes within it so at execution time the$cmdvariable 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 GreenRunning Invoke-Expression -Command $cmd; outputs this (in green of course)
-H 10.1.1.101 -Disk DataStoreH101 -Disk DataStoreS101