How can I change the headings of hash table columns in powershell script
13,617
Solution 1
Pipe the hashtable to a Select
command, and build your output on the fly such as:
$My_Hash.keys | Select @{l='App1';e={$_}},@{l='App2';e={$My_Hash.$_}}
Solution 2
Building on TheMadTechnician's example, you can make a generic function to rename the "columns":
function Format-Hashtable {
param(
[Parameter(Mandatory,ValueFromPipeline)]
[hashtable]$Hashtable,
[ValidateNotNullOrEmpty()]
[string]$KeyHeader = 'Name',
[ValidateNotNullOrEmpty()]
[string]$ValueHeader = 'Value'
)
$Hashtable.GetEnumerator() |Select-Object @{Label=$KeyHeader;Expression={$_.Key}},@{Label=$ValueHeader;Expression={$_.Value}}
}
Then call it like:
PS C:\> $my_hash |Format-Hashtable -KeyHeader App1 -ValueHeader App2
App1 App2
---- ----
1 2
Author by
Melody975
Updated on June 04, 2022Comments
-
Melody975 almost 2 years
I am fairly new to Powershell scripting. I am writing a power-shell script in which I declared a hash table like the following:
$a = 1 $b = 2 $my_hash = @{} $my_hash.Add($a, $b)
When I print the table in Powershell, the headings of the hash table shows
Name Value ---- ----- 1 2
How can I change the name of each column from "Name, Value" to something like "Application1, Application2"? I.e.
App1 App2 ---- ----- 1 2
Appreciate the help!