2012-05-25 17 views
19

Mam hashtable:String wartości HashTable w PowerShell

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

wiem, że mogę to zrobić:

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

Więc miałem nadzieję zrobić to:

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

... ale otrzymuję:

Hello, . 

Jak mogę odwołać się do elementów tablicy mieszającej w interpolacji ciągów?

Odpowiedz

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

tych dodatkowych '$' symbole są dość brzydki. Miałem nadzieję na coś ładniejszego. –

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

Wymaga to dodatkowych nawiasów: Write-Host ("Hello {0} {1}." -f ...) –

3

Z dodatkiem niewielkiej funkcji, możesz być nieco bardziej ogólne, jeśli chcesz. Uważaj jednak, że uruchamiasz potencjalnie niezaufany kod w ciągu znaków $template.

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

nie udało się uzyskać Lemur's answer do pracy w PowerShell 4.0 tak dostosowane następująco

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) 
} 
Powiązane problemy