我有一個帶有陣列的嵌套哈希表,我想遍歷另一個陣列的內容并將其添加到嵌套哈希表中。我正在嘗試構建一個 Slack 訊息塊。
這是我要添加到的嵌套哈希表:
$msgdata = @{
blocks = @(
@{
type = 'section'
text = @{
type = 'mrkdwn'
text = '*Services Being Used This Month*'
}
}
@{
type = 'divider'
}
)
}
$rows = [ ['azure vm', 'centralus'], ['azure sql', 'eastus'], ['azure functions', 'centralus'], ['azure monitor', 'eastus2'] ]
$serviceitems = @()
foreach ($r in $rows) {
$servicetext = "*{0}* - {1}" -f $r[1], $r[0]
$serviceitems = @{'type'='section'}
$serviceitems = @{'text'= ''}
$serviceitems.text.Add('type'='mrkdwn')
$serviceitems.text.Add('text'=$servicetext)
$serviceitems = @{'type'='divider'}
}
$msgdata.blocks = $serviceitems
該代碼部分作業。哈希表 @{'type'='section'} 和 @{'type'='divider'} 成功添加。嘗試添加 @{'text' = @{ 'type'='mrkdwn' 'text'=$servicetext }} 的嵌套哈希表失敗并出現以下錯誤:
Line |
24 | $serviceitems.text.Add('type'='mrkdwn')
| ~
| Missing ')' in method call.
我嘗試瀏覽各種 Powershell 帖子,但找不到適用于我具體情況的帖子。我是在 Powershell 中使用哈希表的新手。
uj5u.com熱心網友回復:
作為 mklement0 的有用答案的補充,它解決了您現有代碼的問題,我建議使用行內哈希表進行以下重構:
$serviceitems = foreach ($r in $rows) {
@{
type = 'section'
text = @{
type = 'mrkdwn'
text = "*{0}* - {1}" -f $r[1], $r[0]
}
}
@{
type = 'divider'
}
}
$msgdata.blocks = $serviceitems
在我看來,這看起來更干凈,因此更容易維護。
說明:
$serviceitems = foreach ...捕獲變數中回圈的所有輸出(到成功流)。PowerShell 自動從輸出中創建一個陣列,這比使用運算子手動添加到陣列更有效。使用PowerShell 必須為每次添加重新創建一個新大小的陣列,因為陣列實際上是固定大小的。當 PowerShell 自動創建陣列時,它會在內部使用更高效的資料結構。foreach$serviceitems==- 通過寫出行內哈希表,而不將其分配給變數,PowerShell隱式輸出資料,實際上將其添加到
$serviceitems陣列中。 - 我們每次回圈迭代輸出兩個哈希表,因此 PowerShells 在每次回圈迭代中添加兩個陣列元素
$serviceitems。
uj5u.com熱心網友回復:
筆記:
這個答案解決了你的問題,特別是它的語法問題。
有關繞過原始問題以支持簡化代碼的卓越解決方案,請參閱zett42 的有用答案。
$serviceitems.text.Add('type'='mrkdwn')導致語法錯誤。
一般來說,如果$serviceitems.text參考哈希表(字典),您需要:
- 具有不同的 -
,分隔引數的方法語法:
$serviceitems.text.Add('type', 'mrkdwn')
- 或索引語法(如果存在,它將悄悄地覆寫現有條目):
$serviceitems.text['type'] = 'mrkdwn'
PowerShell 甚至允許您使用成員訪問語法(點表示法)訪問哈希表(字典)條目:
$serviceitems.text.type = 'mrkdwn'
在您的具體情況下,需要考慮其他注意事項:
您正在通過陣列而不是直接訪問哈希表。
您嘗試定位的
text條目最初不是嵌套哈希表,因此您無法呼叫.Add()它;相反,您必須為其分配一個新的哈希表。
所以:
# Define an empty array
$serviceItems = @()
# "Extend" the array by adding a hashtable.
# Note: Except with small arrays, growing them with =
# should be avoided, because a *new* array must be allocated
# every time.
$serviceItems = @{ text = '' }
# Refer to the hashtable via the array's last element (-1),
# and assign a nested hashtable to it.
$serviceItems[-1].text = @{ 'type' = 'mrkdwn' }
# Output the result.
$serviceItems
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474183.html
標籤:电源外壳
下一篇:合并組集合中的兩個組
