簡體   English   中英

如何使用 Format-Table 格式化 PowerShell 多維數組

[英]How to format PowerShell multidimensional array with Format-Table

我想使用 Format-Table 發送 PowerShell 多維數組的 output。

這是我的示例代碼:

$a = ('mickey', 1,'pluto'),('qwer', 2, 'fluffy'),('prague', 1, 'new york')

foreach ($i in $a) {
    $value = 0
    if (($i[0] -eq 'mickey') -and ($i[2] -eq 'asdf')) {
        $i[1]++
        break
    } else {
        $value = 1
    }
}


if ($value -eq 1) {
    $a += ,@('mickey', 1, 'asdf')
    $value = 0
}

$a

哪個會 output:

mickey
1
pluto
qwer
2
fluffy
prague
1
new york
mickey
1
asdf

我想使用 PowerShell 格式表來格式化這個 output。 分離看起來很整潔,我發送給它的代碼比你看到的要大。

我知道我可以使用foreach並將其與文本並排循環:

for ($i=0; $i -lt $a.length; $i++) {
    $a[$i][0] + " " + $a[$i][1] + " " + $a[$i][2]
}

然而 output 視圖不是我喜歡的,每個部分的 header 之類的會很好。

我在想這樣的事情,但可惜我無法讓它工作: $a | Format-Table -Property @{Name = 'Name'; Expression = {$_[0]}; Width = 20; Align = 'left'} $a | Format-Table -Property @{Name = 'Name'; Expression = {$_[0]}; Width = 20; Align = 'left'}

歡迎任何想法/指導。

通過Select-Object定義將構成表格列的屬性,然后才傳遞給Format-Table Format-Table cmdlet 需要 object(例如[PSCustomObject] )作為Select-Object生成的輸入。

$a | Select-Object -Property @{ Name = 'Name'; Expression = { $_[0] } } |
     Format-Table -Property @{ Expression = 'Name'; Width = 20; Align = 'left' }

我們使用一個技巧來簡化Format-Table行。 通過將字符串而不是腳本塊分配給Expression ,我們 select 應應用格式化的列。 這相當於:

Format-Table -Property @{ Name ='Name'; Expression = { $_.Name }; Width = 20; Align = 'left' }

Output:

Name
----
mickey
qwer
prague
mickey

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM