Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the headings of hash table columns in powershell script

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!

like image 651
Melody975 Avatar asked Aug 16 '16 17:08

Melody975


People also ask

How does PowerShell define hash table?

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.

How do you access a Hashtable in PowerShell?

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.

How do I use AutoSize in PowerShell?

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.


2 Answers

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.$_}}
like image 163
TheMadTechnician Avatar answered Nov 15 '22 04:11

TheMadTechnician


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
like image 20
Mathias R. Jessen Avatar answered Nov 15 '22 03:11

Mathias R. Jessen