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!
To create a hash table in PowerShell, you'll use an @ symbol followed by an opening curly brace and a closing curly brace as shown below. Here you can see my hash table is now three lines with a key/value pair in the middle.
Object Types in HashTables You can display the hash table in $p and use the key-name properties to display the values. The keys in a hash table can also be any . NET type. The following statement adds a key/value pair to the hash table in the $p variable.
If you specify the AutoSize parameter when you run the Format-Table command, PowerShell calculates column widths based on the actual data displayed. This makes the columns readable. The Format-Table cmdlet might still truncate data, but it only truncates at the end of the screen.
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.$_}}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With