Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation of hashtable values in PowerShell

Tags:

powershell

I've got a hashtable:

$hash = @{ First = 'Al'; Last = 'Bundy' } 

I know that I can do this:

Write-Host "Computer name is ${env:COMPUTERNAME}" 

So I was hoping to do this:

Write-Host "Hello, ${hash.First} ${hash.Last}." 

...but I get this:

Hello,  . 

How do I reference hash table members in string interpolation?

like image 971
Roger Lipscombe Avatar asked May 25 '12 12:05

Roger Lipscombe


People also ask

How do I iterate through a Hashtable in PowerShell?

In the first method, the one that I prefer, you can use the GetEnumerator method of the hash table object. In the second method, instead of iterating over the hash table itself, we loop over the Keys of the hash table. Both of these methods produce the same output as our original version.

What is @() in PowerShell?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.

How do I string a variable in PowerShell?

PowerShell declares a variable by using the $ sign and the variable name. For example, $Services. When we declare any type (Integer, double, string, DateTime) of the variable and when we use them inside the string variable, it automatically converts that variable to the string.


2 Answers

Write-Host "Hello, $($hash.First) $($hash.Last)." 
like image 96
David Brabant Avatar answered Sep 20 '22 15:09

David Brabant


"Hello, {0} {1}." -f $hash["First"] , $hash["Last"]     
like image 23
Angshuman Agarwal Avatar answered Sep 23 '22 15:09

Angshuman Agarwal