PowerShell Array and Add to Array: Applications and Examples

-

|

What is a PowerShell Array?

A PowerShell array is a data structure that stores a collection of items. The items stored may be the same or different types.

In some part of this tutorial I could refer to PowerShell simply as PS.

Creating a PowerShell array is as simple as creating a variable and adding items (in double quotes “”) into the variable separated by commas (,).

As an example, to create a PS array called $ArrayEg, run the command bellow:

$ArrayEg = "A","B","C","D"

Note that the items on the right side of the equation is in double quotes, separated by commas. To confirm that this created a PS Array, run the command below:

$ArrayEg.GetType()

The result is shown below:

Notice that the BaseType is System.Array.

If you are creating a PowerShell script Arrays are very helpful. Let’s say you need to add some Active Directory users to a set of security groups. You can create an array containing the AD groups as shown below:

$Groups = "Group1", "Group2", "Group3" 

With the security groups in a Array, you can iterate through the array items using a ForEach loop. A ForEach loop will allow you to add the users into each security group in the Array.

Manipulating an Array

A PS Array has some characteristics that you may want to know about. For instance, you might want to find the data type of a PowerShell array. To find the data type of a PowerShell array, use the GetType() method. For example, to get the data array type of ‘$Groups’ PowerShell array created earlier, run the command below:

$Groups.GetType()  

You can also find additional properties contained in a PowerShell array by piping the array into the Get-Member cmdlet. You might be wondering why you need all these information about an array. Later in the tutorial I will provide additional examples that will clarify why you may need additional information about the Array you are working with.

To find all properties and methods in the PowerShell array $Groups, simply pipe $Groups to the Get-Member cmdlet. See the command below:

$Groups | Get-Member  

Result of the previous command is shown below:

powershell-array-image-1

In the image notice that there are properties and methods (some part of the image is not shown). Properties represents the actual properties of the PowerShell array. Methods allow you to run commands against the array as shown with the GetType() command previously used in this article.

To learn more about object properties, methods and other PowerShell scripting skills, refer to the references at the end of this page.

How to Access the Items in a PowerShell Array

Earlier in this tutorial, I defined a PS Array as a data structure that stores a collection of items. We also created a simple PowerShell array called $ArrayEg. Let’s revisit this one more time. To proceed, execute the command below:

$ArrayEg = "A", "B", "C", "D"  

To list the content of the array, simply execute $ArrayEg as shown below:

$ArrayEg  

The previous command will list the values A, B, C, D in that order. There might be circumstances when you need to access one of the items contained in the array. Before I show you how to run the command that returns the items contained in the PowerShell array, it is important to understand how the array contents are arranged.

You can access the elements in an array by using an index. The first value (position zero) of the PowerShell array is assigned a zero ‘0’. So, item ‘A’ occupies position zero, ‘B’, position one ‘1’ and so on. To return the first item in the Array, run the command below:

($ArrayEg)[0]

The command returns ‘A’ as shown below:

To return the second item, ‘B’, replace ‘0’ with ‘1’ in the previous command.

Practical Application of a PowerShell Array

Up to this point, I have been showing you the theoretical side of a PS Array. But as a Windows Admin I believe you will be keen to learn how you can apply this to a real task.

To this end, I will now show you one application of PowerShell Arrays in reporting processes that are consuming the most resources in a computer.

PowerShell Array Application in Reporting Top CPU Processes

In this example, I will demonstrate how you can use the knowledge you have gained so far about PowerShell Array to find the process that has the top CPU utilization in your pc.

The first step is to get all the process and store them in a variable called $Proc. This is achieved by the command below:

 $Proc = Get-Process 

The command simply stores the processes on my local pc in the $Proc variable. To see the information stored, execute the command below.

$Proc

The result of the previous command is shush below:

Array application in reporting top CPU processes

Take a closer look at CPU(s) column. This column shows the CPU consumption of each process.

To confirm that the previous command created an Array, execute the command below:

$proc.GetType()

How to Find the Processes with the Highest CPU Consumption

Before we can find the processes with top CPU consumption, we need to sort the process in order of CPU consumption. To achieve this, pipe the $Proc PowerShell array to the Sort-Object cmdlet. The Sort-Object cmdlet sorts the content of the PowerShell array in ascending order. Below is the command.

$Proc | Sort-Object CPU  

Unfortunately the previous command did not sort the items in the order we want them. See the result of the command below.

We will like to have the items sorted in descending order – so that processes with top CPU utilization are on top of the list.

Sorting the items in descending order is very simple. It requires us to include the Descending parameter of the Sort-Object cmdlet. See the amended command below.

$Proc | Sort-Object CPU -Descending  

Here is the result of the command

Notice that the items are now sorted in order of CPU consumption. The process with the highest CPU utilization is now on top. At this point, we can return the process with top CPU utilization. The command below does the magic!

($Proc | Sort-Object CPU -Descending)[0]

This was achieved by returning the first item in the array – that is after it has been sorted. See image below for clarification.

The will return the first item in the PowerShell array. This is the process with top CPU consumption. How good is that!

PowerShell Add to Array

In the final part of this tutorial I will like to show you how to add items to a PowerShell Array. Adding an item to an existing PS Array requires the use of the Add() method.

To illustrate this lets get back to our $ArrayEg example. To create the PS Array $ArrayEg, we executed the command below:

$ArrayEg = "A","B","C","D"

Now see the Array members, execute $ArrayEg – see the result below:

PowerShell Add to Array

Let’s now add item “E” to the Array – the command below will complete the task:

$ArrayEg.Add("E")

Unfortunately, trying to add an item to an existing array returns an error – see image below:

How to Resolve the PowerShell Add to Array Error

We resolve this error in 2 ways.

One, by using the System.Collections.ArrayList as shown below:

[System.Collections.ArrayList]$ArrayEgList = $ArrayEg

Now you can successfully execute the previous command that failed but this time using the created Array List, $ArrayEgList.

 $ArrayEgList.Add("E) 

Next, execute $ArrayEgList to see that “E” was added successfully. See image below for the result of both commands:

PowerShell Add to Array - ArrayList

Another way to add an ietm to an existing PS Array is to use the method illustrated in the command below:

$ArrayEg2 = $ArrayEg += "E"

References and Further Reading

  1. Get-Member
  2. Using the Get-Member Cmdlet
  3. about_Arrays
  4. Sort-Object
  5. Using the Sort-Object Cmdlet

Quick Links to Similar Tutorials

  1. 18 Powershell Commands Every Windows Admin Should Know
  2. ForEach PowerShell: Applications with examples
  • Was this post Helpful?
  • YesNo

LEAVE A REPLY

Please enter your comment!
Please enter your name here

ADVERTISEMENTS

FEATURED POSTS

Best Christian Movies on Netflix

The 10 Best Christian Movies on Netflix

This Itechguide reviews the 10 best christian movies on Netflix. The movies are listed in reverse order – with the 10th movie...
How to Change Orientation in Google Docs

How to Change Orientation in Google Docs

This Itechguide teaches you how to change orientation in Google Docs. The guide covers steps to change orientation in Google Docs from...
How to Delete Google Photos

How to Delete Google Photos

This Itechguide teaches you how to delete Google Photos. The guide offers steps to delete Google Photos from the Google Photos App...
How to Install Windows 10 1909 Update Manually

How to Install Windows 10 1909 Update Manually

This Itechguide teaches you how to install Windows 10 1909 update manually. Windows 10 1909 (otherwise known as Windows 10 November update)...
How to Create a Poll on Facebook

How to Create a Poll on Facebook

This Itechguide teaches you how to create a poll on Facebook. You can create a poll on Facebook from a Facebook page...

AMAZON DEALS

TRENDING POSTS

Remote Desktop Connection

Remote Desktop Connection an Internal Error Has Occurred [Fixed]

Introduction I recently received the error message "Remote Desktop Connection an Internal Error Has Occurred". It was strange because...

Find My Samsung: Register and Use Samsung Find my Mobile

Introduction Ever wondered how you could find your Samsung phone if you lost it? Find my Samsung or Samsung...
What is the Difference Between PowerShell and CMD?

Windows Powershell vs CMD: Differences and Similarities

Introduction This short guide compares Windows PowerShell vs CMD (Windows command prompt). I will cover the history and nature...
Spotify No Longer Supports this Version of Microsoft Edge

Spotify No Longer Supports this Version of Microsoft Edge [Fixed]

Introduction When you open Spotify web player on Microsoft Edge, you may receive the error message "Spotify No Longer...
Windows 10 Won't Boot

Windows 10 Won’t Boot With Black Screen? 3 Ways to Fix It

Why Won't Windows 10 Boot Up? If your Windows 10 stops with a black screen, the first question in...

ADVERTISEMENTS

BEST OF ITECHGUIDES

The 10 Best Korean Movies on Netflix

The 10 Best Korean Movies on Netflix

Korean movies are making wave in the movie world globally. There are several Koreans movies on Netflix with different genre.
How to Untag Someone on Facebook

How to Untag Someone on Facebook (from a Smartphone or PC)

Introduction This guide demos how to untag someone on Facebook from the Facebook the App or a PC.
How to Download YouTube Video Without Software

How to Download YouTube Video Without Software

This Itechguide teaches you how to download YouTube video without software. The guide offers 2 simplified steps. Get...

How to Create Windows 10 Installation Media with Media Creation Tool

Introduction Don't have a Windows 10 installation media? You can create Windows 10 Installation Media with Media with Windows...
how-to-flip-an-image-in-google-docs

How to Flip an Image in Google Docs

This guide demos how to flip an image in Google Docs. Flipping an image is different from rotating...

RECENT POSTS

How to Change Facebook Page Name

How to Change Facebook Page Name

This Itechguide teaches you how to change Facebook page name. The guide covers steps to change Facebook page name from a PC...
How to Change YouTube Channel Name

How to Change YouTube Channel Name

This Itechguide teaches you how to change YouTube channel name. The guide covers steps to change YouTube channel name from a PC.
How to Bold Text on Facebook Post

How to Bold Text on Facebook Post

This Itechguide teaches you how to bold text on Facebook post. The guide covers steps to bold text on Facebook post from...
Best Crime Documentaries on Netflix

The 10 Best Crime Documentaries on Netflix

This Itechguide reviews the 10 best crime documentaries on Netflix. The documentaries are listed in reverse order – with the 10th documentary...
Best Netflix Series

The 10 Best Netflix Series

This Itechguide reviews the 10 best Netflix series. The series are listed in reverse order – with the 10th series on top....

AMAZON DEALS

MUST READ

How to Change Administrator Name in Windows 10 (4 Methods)

How to Change Administrator Name in Windows 10

Introduction This guide demos how to change administrator name in Windows 10. There could be...
How to Remove Google Account from Chrome

How to Remove Google Account from Chrome

This Itechguide teaches you how to remove Google account from Chrome. The guide has 3 sections - steps to remove Google account...
How-to-Calculate-Standard-Deviation-in-Excel

How to Calculate Standard Deviation in Excel

Introduction Standard Deviation is a measure of how dispersed values are from their mean (average). You can calculate standard...
YouTube Music Playlist

YouTube Music Playlist: How to Create Playlists and Add Songs

Introduction A YouTube music playlist allows you to add a collection of songs or videos into a single location....
FTP and SFTP ports

FTP and FTP Port, SFTP and SFTP Port: Quick Reference

Introduction FTP and SFTP are two protocols for transferring files between a server and a client computer. FTP port...

AMAZON DEALS

By using this website you agree to accept our Privacy Policy and Terms & Conditions