2016-10-14 22 views
2

這對於某人來說肯定是容易的事情。當我在一個字符串中引用數組項時,它不會產生所需的結果。我期望最後一條語句產生一個包含「abc」的字符串,但事實並非如此。如何在一個字符串中擴展(插入)數組元素

PS C:\src\powershell> $mylist = @("abc", "def") 
PS C:\src\powershell> $mylist 
abc 
def 
PS C:\src\powershell> $mylist[0] 
abc 
PS C:\src\powershell> $mylist[1] 
def 
PS C:\src\powershell> "$mylist[0]" 
abc def[0]s 

回答

3

注:雖然這個回答涵蓋了PowerShell的串插在許多方面,該主題的更全面的治療可以在我的this answer被發現。

當嵌入在雙引號字符串變量引用僅簡單變量引用可以嵌入而不包圍在所謂的子表達式運算符,$(...)表達式:

> $mylist = @("abc", "def") # define an array 

> "$mylist[0]" # WRONG: $mylist (the whole array) is expanded, and "[0]" is a literal. 
abc def[0] 

> "$($mylist[0])" # OK: $(...) ensures that the subscript is recognized. 
abc 

要更精確,可以直接嵌入以下變量引用雙引號ED串/以便讓他們膨脹(插值)這裏串

  • 一個可變用名字引用;例如"I'm $HOME."
  • a 變量與範圍說明符;例如,"I'm on a spiritual $env:PATH."

消除歧義變量名從後續字符,它括在{...};例如,
"I'm ${HOME}:"
請注意,如果沒有{...},最終的:將被解釋爲變量名稱的一部分,並且會導致錯誤。
或者,您可以逃避:`:,同樣,使用`$逃脫(創建字面$

對於一切,包括訪問數組變量的下標對象變量的財產,你需要的次表達式運算,$(...)
請注意,$(...)允許您將整個命令行嵌入到字符串中;例如:

> "Today is $((Get-Date).ToString('d'))." 
Today is 10/13/16.       # en-US culture 

文檔注:Get-Help about_Quoting_Rules涵蓋串插,但是,PSv5的,不深入。


對於替代串插(擴大)建設字符串,見Ansgar Wiecher's answer

1

在擴展字符串中的變量時,PowerShell無法識別更復雜的變量結構(例如索引操作($mylist[0])或屬性/方法訪問($mylist.Count))。它將簡單地擴展變量並將剩下的字符串單獨留下。因此表達式"$mylist[0]"變成"abc def[0]"

基本上,你有三種選擇,以應對這一限制:

當然也有更多的 「異國情調」 的方法,如使用-join操作:

"-", $mylist[0], "-" -join "" 

或替換操作:

'-%x%-' -replace '%x%', $mylist[0] 
'-%x%-'.Replace('%x%', $mylist[0]) 

但那些已經在模糊邊緣。

相關問題