ハッシュの配列を表形式(Format-Table)で表示する方法 †
ハッシュに同じキーで各種値を設定した情報を配列で持っている変数を表形式で表示する方法を以下に記します。
関連記事 †
PSCustomObjectを使用する †
以下の通り、実際にハッシュ変数の配列変数作成し、表形式で表示させてみます。
- ハッシュ変数の配列を準備
以下のように、ハッシュの配列を作成します。
$hls = (
@{Distribution="Ubuntu"; ostype="Linux"; base="Debian"},
@{Distribution="Debian"; ostype="Linux"; base="Independent"},
@{Distribution="Red Hat Enterprise Linux"; ostype="Linux"; base="Fedora"},
@{Distribution="FreeBSD"; ostype="BSD"; base="Independent"},
@{Distribution="TrueOS"; ostype="BSD"; base="FreeBSD"},
@{Distribution="OpenBSD"; ostype="BSD"; base="Independent"}
)
- 上記の構文を実際にPowerShell上で実行したときの出力です。
上記でハッシュの配列を格納した$hls変数を確認のため表示させています。
PS C:\> $hls = (
>> @{Distribution="Ubuntu"; ostype="Linux"; base="Debian"},
>> @{Distribution="Debian"; ostype="Linux"; base="Independent"},
>> @{Distribution="Red Hat Enterprise Linux"; ostype="Linux"; base="Fedora"},
>> @{Distribution="FreeBSD"; ostype="BSD"; base="Independent"},
>> @{Distribution="TrueOS"; ostype="BSD"; base="FreeBSD"},
>> @{Distribution="OpenBSD"; ostype="BSD"; base="Independent"}
>> )
PS C:\> $hls
Name Value
---- -----
Distribution Ubuntu
ostype Linux
base Debian
Distribution Debian
ostype Linux
base Independent
Distribution Red Hat Enterprise Linux
ostype Linux
base Fedora
Distribution FreeBSD
ostype BSD
base Independent
Distribution TrueOS
ostype BSD
base FreeBSD
Distribution OpenBSD
ostype BSD
base Independent
- PSCustomObjectを使って、表形式にします。
$fls = $hls | % { New-Object PSCustomObject -Property $_ }
- 上記の構文を実際にPowerShell上で実行したときの出力です。
PS C:\> $fls = $hls | % { New-Object PSCustomObject -Property $_ }
PS C:\> $fls
Distribution ostype base
------------ ------ ----
Ubuntu Linux Debian
Debian Linux Independent
Red Hat Enterprise Linux Linux Fedora
FreeBSD BSD Independent
TrueOS BSD FreeBSD
OpenBSD BSD Independent
- Format-TableのPropertyに項目名を指定すれば、指定した項目のみ表示できます。
PS C:\> $fls | Format-Table -Property Distribution, base
Distribution base
------------ ----
Ubuntu Debian
Debian Independent
Red Hat Enterprise Linux Fedora
FreeBSD Independent
TrueOS FreeBSD
OpenBSD Independent
以上、ハッシュの配列を表形式で表示する方法でした。