How to Remove an Item From a PowerShell Array (2024)

While most tasks involving arrays in PowerShell are relatively easy, removing an item from an array presents a challenge. PowerShell lacks a native cmdlet designed specifically for removing items from an array. Even so, there are two methods you can use, both of which I will explain in this article.

Method #1: The Easy Way

The easy way ofremoving an item from a PowerShellarrayis to set the item'sindex position to $Null. This action essentially makes PowerShell treat the position as if it no longer exists. Let me show you how this works.

To get started, let’s create an array containing the letters A through F. You can do this by entering this command:

$A=@(‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’)

Typing $A causes PowerShell to display the items in the array, as shown in Figure 1.

How to Remove an Item From a PowerShell Array (1)

Array Remove 1

Figure 1. The array $A contains the letters A through F.

It’s important to understand that each element in an array (represented by the letters A through F) corresponds to a numerical index value. The indexing starts at 0, meaning that $A[0] is equal to A, $A[1] is equal to B, and so forth. Since there are six letters stored in the array, the index values range from 0 to 5, where $A[5] contains the letter F.

With that in mind, let’s suppose that we want to remove the letter D from the array. The simple way to do this is to set the index position associated with the letter D to $Null. Here’s the command:

Related:How To Split a String in PowerShell: Examples and Code update from March 2023

$A[3]=$Null

If youtype $A to display the array’s contents now, the letter D is gone, as shown in Figure 2.

How to Remove an Item From a PowerShell Array (2)

Array Remove 2

Figure 2. Setting an array position to $Null removes the value from the array.

Given the ease with which I just removed an array item, you may be wondering why I am even going to bother explaining the hard way of doing this. The reason why is that we haven’t truly removed the item from the array. Although the value is gone, the array still retains six positions (you can check by typing $A.count). Additionally, the letter E remains in the 4th index position, and F is still in the 5th index position, just as it was before I removed the letter D.

How to Remove an Item From a PowerShell Array (3)

Array Remove 3

Figure 3. The array position has not been deleted.

In some cases, the method that I just showed you may be perfectly fine. In other cases, having empty array positions can really cause problems. This is why I will explain the hard way of removing an item from an array.

Method #2: The Hard Way

According to Microsoft documentation, adding an item to an array involves creating a brand-new array. Thankfully, PowerShell handles this process seamlessly. However, when it comes to truly removing an item from an array, you also must construct a brand-new array. The difference is that PowerShell doesn’t automatically handle this.

Here is how you can truly remove an item from an array:

$A=@('A','B','C','D','E','F')$A$Index=0$TotalItems=$A.countForEach ($Item in $A){ If ($Item -eq 'D') {$Position=$Index} $Index=$Index+1 }Write-Host 'the position is ' $Position# Copy the letters before D$B=@($Null)For ($Counter=0; $Counter -lt $Position; $Counter++) { $B+=$A[$Counter] }#Copy the letters after DFor ($Counter=$Position+1; $Counter -le $TotalItems; $Counter++) { $B+=$A[$Counter] }$A = $B$A

This script does the same thing that we did a moment ago: It removes the letter D from the array.

The script starts by creating the array in the same way as before. It then sets a variable called $Index to 0 and sets a variable called $TotalItems equal to the total number of items in the array (6).

Next, a ForEach loop looks at every position in the array to see if its value is equal to D.

When the loop does find the letter D in the array, it stores its index value in a variable called $Position. In other words, $A[$Position] corresponds to the letter D. Being that we already know that the letter D is in the 3 position, we could have just set $Position to be equal to 3 and not bothered creating this loop. In real-world scenarios, however, the position is often unknown.

Next, I have created an empty array called $B. I am using two loops to populate the $B array with the data from the $A array. The first loop copies all the data that comes before the letter D (positions 0, 1, and 2). The second loop copies the data that comes after the letter D (positions 4 and 5).

The first of the two loops sets a variable called $Counter equal to 0. It then increments that counter by 1 every time the loop cycles. The loop continues so long as the counter value is less than the $Position variable, which holds the index value for D. Each time the loop cycles, it copies $A[$Counter] to the $B array. In this case, that means that the loop will copy $A[0], $A[1], and $A[2].

The second loop starts with the counter set to $Position + 1, or the position after the letter D. It then copies this position and all other positions (up to the $TotalItems in the array) to the $B array.

At this point, we have created a brand-new array called $B. The array contains all the data from $A except for the letter D. Because it is a new array, D and its position are truly gone.

The last step in the process is to copy the $B array to $A. The result is that the $A array contains all of the same data as before, minus the letter D. Unlike the first method I explained, the value D is truly removed from the array along with its position, and the index values for E and F have changed to reflect the removal of D.

How to Remove an Item From a PowerShell Array (2024)
Top Articles
How to Pass Amazon Area Manager Job Interview and Hiring Assessment Test: All You Need to Know!
How to Get a Startup Business Loan With No Money
How to Search All of Craigslist at Once | Digital Trends
Caroline Cps.powerschool.com
Christine Paduch Howell Nj
Notorious CT After-Hours Club Raided, Nets 3 Arrests, More To Come, Police Say
John Bobbitt Net Worth
Waifu Fighter F95
Pokemon Radical Red Move Tutor
Qr 0738
Spotlight: Columbus, Ohio - from cowtown to server farm
Chase Bank Time Hours
Section 102 Allstate Arena
Paisanos Duncan Sc Menu
Homepoint Financial Wholesale Login
450 Miles Away From Me
Knox Horizon Complete Auto Care Reviews
Lesson 12 Homework 4.5 Answer Key
Spirited Showtimes Near Cinemark At Antelope Valley Mall
What's My Wells Fargo Routing Number?
4 Pm Edt
Ww2 Solarmovie
New England Revolution vs CF Montréal - En vivo MLS de Estados Unidos - 2024 - Fase Regular
Former Woodland Hills football standout dies in Larimer shooting
Eli Lilly Clarifies It’s Not Offering Free Insulin After Tweet From Fake Verified Account—As Chaos Unfolds On Twitter
Regionale Kennis van Uitvaarten • Funeral Assist
Www.doculivery/United Family Payroll Login Page
Williamson Funeral Home Staunton Obituaries
Chromazz Bikini
Stanley Steemer Medford Oregon
Willow Returns 34 Years Later in an Exciting New Series on Disney+
Jail View Santa Rosa County Jail View
Habbowidget
Sailboat - sailing yacht - for sale
2 Cor 9 Nlt
Marketplace Palm Coast
Bloxburg Bedroom Inspiration: Sweet & Cozy Designs
Halloween showing of Hocus Pocus on Thirsks Outdoor cinema, Station Road,Thirsk,YO7 1QL,GB, Northallerton, 11 October 2024
Brooke Monk Twitter Deepfake
Speechwire Login
Her Triplet Alphas Chapter 26 Free
Mature Juggs
Town Of Kearny Recycling Calendar
Hope Sign In Nyc
It Lives Inside Showtimes Near Cinemark Grand Cinemas
Livvy Fune
Quiktrip Gas Price Today
Kendal Mint Cake Recipe: A Sweet Adventure - Simple Home Cooked Recipes
Learnnow Pizza Hut
Vera Bradley Factory Outlet Sunbury Photos
Overton's Free Catalog
Latest Posts
Article information

Author: Laurine Ryan

Last Updated:

Views: 5929

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.