How to Create a Table in PowerShell

Tables are a great way to organize data in an easy-to-read format. PowerShell can be used to create tables within PowerShell scripts. This article will show various ways of creating PowerShell tables and the code required for each table type.

A table is an efficient way of displaying information in rows and columns so it is easier for readers to find what they want quickly, without having to scroll horizontally across the page.

In some cases when working with simple objects there is no need to create a table in order to display data and we can easily use the built-in format-table function. The problems start when we deal with complex objects where format-table can’t handle the data or the returned data.

Create a Table

In the below code example, I’m using the Azure AD cmdlet that to extract all the audit logs. Because the returned values contain many fields which I don’t need I’m creating a custom table that displays only the data that I need.

The first two lines of code initialize two arrays, the first one (array) stores all the Azure audit logs. the second line creates an empty array (data) that will store the table.

$array = Get-AzureADAuditSignInLogs
$data [email protected]()

Line #3 is a foreach statement that loops the array and extracts each item from it.

The if statement in line #4 adds a condition the removes empty items from the table.

Line #7 creates the top row and columns and the names of each column.

and #8 populate each row.

Line #13 adds each row to the table (data) and the last line displays the table when all the items have been looped over by the foreach loop.

 $row = "" | Select-Object User,UPN,City,State,Region
 $row.user = $item.UserDisplayName

You can see the entire code below.

$array = Get-AzureADAuditSignInLogs
$data [email protected]()
foreach($item in $array)
{
   if($item.location.CountryOrRegion -notlike $null )
   {
      $row = "" | Select-Object User,UPN,City,State,Region
      $row.user = $item.UserDisplayName
      $row.upn = $item.UserPrincipalName
      $row.city = $item.Location.City
      $row.state = $item.Location.State
      $row.region = $item.Location.CountryOrRegion
      $data += $row 
   }

}
$data | Format-Table -AutoSize
,

Processing…
Success! You're on the list.

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.