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.

Sponsored Content


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.

Sponsored Content


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()

Sponsored Content


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:

Sponsored Content


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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

FEATURED POSTS

network discovery keeps turning off server 2016

How to Fix Network Discovery If it Keeps Turning Off in Server 2016

Does network discovery keep turning off in your Windows server 2016? It is likely that one of its dependent services is not...
how to install windows 10 1903 update manually

How to Install Windows 10 1903 Update Manually

Windows 10 1903 Update was released in May, 2019. But some users are not yet offered the update via automatic update. The...
spotify web player not working

Spotify Web Player Not Working [Fixed]

Introduction Spotify Web Player may stop working for you with the following error messages: "Spotify Web Player an Error...
DISM.exe /Online /Cleanup-Image /Restorehealth

DISM.exe /Online /Cleanup-Image /Restorehealth Explained

What is DISM.EXE /Online /Cleanup-image /RestoreHealth? "DISM.exe /Online /Cleanup-Image /Restorehealth" is a DISM command that repairs issue with the...
DHCP Relay agent

DHCP Relay Agent: Configuration in Windows Server 2016

What is a DHCP Relay Agent? A DHCP Relay Agent allows DHCP clients in a different network subnet to...

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...

BEST OF ITECHGUIDES

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...
Group Policy, GPResult, Group Policy Object and RSoP

Group Policy, Group Policy Object and RSoP Explained

Introduction This guide gives an overview of Group Policy, RSoP (Resultant Set of Policy) and Group Policy Objects.
foreach in file powershell

How to Iterate the Content of a Text File in Powershell in 2 Easy...

Introduction If you have a text file with data you wish to use, you can use PowerShell Get-Content ...

Gmail Search by Date: How to Search Gmail by Date

Introduction You can search Gmail by date for emails sent during certain time period. You could also search Gmail...
active directory interview questions

35 Active Directory Interview Questions and Answers

I have compiled 35 Active Directory interview questions and answers. Where necessary, I have also provided additional information to help you understand...

RECENT POSTS

disable cortana windows 10 featured

How to Disable Cortana in Windows 10 (2 Methods)

Introduction Some Windows 10 users may not like Cortana. Solution? Disable Cortana. You are probably reading this because you...
bootrec /fixboot access is denied

How to Fix BootRec /FixBoot Access is Denied Error in Windows 10

Introduction BootRec /FixBoot Access is Denied Error in Windows 10? This error is likely caused by corrupt EFI directory.
Reset Windows 10

How to Reset Windows 10 (2 Methods)

Introduction If your Windows 10 is broken, one available way to fix it is to use Windows 10 reset....
system restore windows 10

How to Enable and Use System Restore in Windows 10

Introduction System restore in windows 10 is a very important tool that is probably ignored by most users. But...
windows has stopped this device code 43

How to Fix Windows Has Stopped this Device Code 43 Error

Introduction Sometimes you may receive "Windows has stopped this device code 43" error. This error is likely to come...
Windows could not automatically detect this network's proxy settings

How to Fix “Windows Could not Automatically Detect this Network’s Proxy Settings”

Introduction You suddenly lose the ability to connect to the internet. Then you run network troubleshooter and it returns...
printer offline

5 Ways to Restore Your Printer Online If Status is Offline

Introduction Is your printer offline? Setting it online is very simple but sometimes it is more than just setting...

How to Fix “BootMgr is Missing” Error in Windows 10

Introduction If you receive Fix "BootMgr is missing" Error in Windows 10, the default response is panic! But you...
windows 10 search featured

How to Fix Windows 10 Search If it Stops Working

Introduction Are you having troubles with Windows 10 search? Apparently, it is a fairly common problem with a number...
oooops, something went wrong. reload

How to Fix “Oooops something went wrong. reload” Spotify Error

Introduction If you receive "Oooops something went wrong. reload" Spotify error, do not panic. The fix is simpler than...

MUST READ

how to share screen on skype

How to Share Screen on Skype on Desktop and Mobile Apps

Introduction What determines how you share screen on Skype depends on a number of factors: Where...
Windows could not automatically detect this network's proxy settings

How to Fix “Windows Could not Automatically Detect this Network’s Proxy Settings”

Introduction You suddenly lose the ability to connect to the internet. Then you run network troubleshooter and it returns...
powershell count

How to Count Objects in PowerShell

Introduction There are so many reasons you may want to count objects in PowerShell. As an example, you may...
Active Directory FSMO Roles

Active Directory FSMO Roles Explained

Introduction This article offers a simplified explanation of the 5 Active Directory FSMO (pronounced "FisMO") roles.
how to change wifi password

How to Change Wifi Password for Any Wifi Router

Introduction To change your Wifi password (PIN), you need the IP address and admin login for the router. Once...

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