2012-05-25 5 views
19

Ich habe eine Hash-Tabelle bekommt:String Interpolation von Hash-Tabelle Wert in Powershell

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

Ich weiß, dass ich das tun kann:

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

So gehofft, ich wurde dies zu tun:

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

... aber ich bekomme diese:

Hello, . 

Wie referenziere ich Hashtabellen in der Stringinterpolation?

Antwort

41
Write-Host "Hello, $($hash.First) $($hash.Last)." 
+7

Diese zusätzlichen '$' Symbole ziemlich hässlich sind. Ich habe auf etwas Schöneres gehofft. –

12
"Hello, {0} {1}." -f $hash["First"] , $hash["Last"]  
+2

Dies erfordert zusätzliche Klammern: Write-Host ("Hallo {0} {1}." -f ...) –

3

Mit der Zugabe einer kleinen Funktion können Sie ein bisschen mehr generisch sein, wenn Sie es wünschen. Achten Sie jedoch darauf, dass Sie potenziell nicht vertrauenswürdigen Code in der Zeichenfolge $template ausführen.

Function Format-String ($template) 
{ 
    # Set all unbound variables (@args) in the local context 
    while (($key, $val, $args) = $args) { Set-Variable $key $val } 
    $ExecutionContext.InvokeCommand.ExpandString($template) 
} 

# Make sure to use single-quotes to avoid expansion before the call. 
Write-Host (Format-String 'Hello, $First $Last' @hash) 

# You have to escape embedded quotes, too, at least in PoSh v2 
Write-Host (Format-String 'Hello, `"$First`" $Last' @hash) 
0

konnte nicht erhalten Lemur's answer 4.0 in Powershell zu arbeiten, so wie folgt angepasst

Function Format-String ($template) 
{ 
    # Set all unbound variables (@args) in the local context 
    while ($args) 
    { 
    ($key, $val, $args) = $args 
    Set-Variable -Name $key.SubString(1,$key.Length-2) -Value $val 
    } 
    $ExecutionContext.InvokeCommand.ExpandString($template) 
} 
Verwandte Themen