Create Tables in PowerShell

Rohan Timalsina Apr 30, 2022
  1. Use Hash Table to Create Tables in PowerShell
  2. Use the DataTable Object to Create Tables in PowerShell
Create Tables in PowerShell

A table is a suitable method for organizing and displaying data in a readable format. A table contains rows and columns to show easier information for users to read.

Creating custom tables is a simple process in PowerShell. This tutorial will introduce different methods to create tables in PowerShell.

Use Hash Table to Create Tables in PowerShell

A hash table is a compact data structure that stores each value using a key. It is also known as a dictionary or associative array.

You can create a hash table in PowerShell using @{}. The keys and values are added in the {} brackets.

$hash = @{Name="brian"; Age="23"; Location="UK"}

A hash table is displayed in the tabular format having one column for keys and another for values.

$hash

Output:

Name                           Value
----                           -----
Name                           brian
Age                            23
Location                       UK

Hash tables only show two columns: Name and Value. So, it is not effective if you need more columns or columns having different names.

Use the DataTable Object to Create Tables in PowerShell

The DataTable object is very useful when working with tables in PowerShell. You can create a DataTable using the command New-Object System.Data.Datatable.

You can use $TableName.Columns.Add("ColumnNames") to add columns and $TableName.Rows.Add("ValueToColumns") to add rows in the table.

The following script creates a table having three columns and three rows.

$table = New-Object System.Data.Datatable

# Adding columns
[void]$table.Columns.Add("Name")
[void]$table.Columns.Add("Age")
[void]$table.Columns.Add("Location")

# Adding rows
[void]$table.Rows.Add("brian","23","UK")
[void]$table.Rows.Add("sam","32","Canada")
[void]$table.Rows.Add("eric","25","USA")

$table

Output:

Name  Age Location
----  --- --------
brian 23  UK
sam   32  Canada
eric  25  USA

In the above example, you have to manually add columns and rows values to show on the table. We hope this article gave you an idea of creating tables in PowerShell.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Table