PowerShell Tip: How to remove items from an Array? Yes, it is possible.


Are you trying to figure out how to remove array items from an Array? Were you end up coding a foreach loop & create a new array?

I have an easy way without using new array or foreach loop. Here it is:

$ArrayVar = $ArrayVar | Where-Object{-not($_ -eq 'ItemValue')}

Now to describe how it been used in a code…I created a quick sample code. Note that I was removing two items at once at line number 9.

$SuperHeros = @("Thor","IronMan","AntMan","Hulk","Clint Barton","DeadPool","Captain Marvel","Black Widow")
"Here are the Super Heros:"
$SuperHeros

"`n`nOops..Black Widow and Clint Barton are not really super heros..Remove them at once."
"Yes Sir."

#Remove Black Widow and Clint Barton...Are they Superheros? or side kicks?
$SuperHeros = $SuperHeros | Where-Object {-not(($_ -eq 'Black Widow') -or ($_ -eq 'Clint Barton'))}

"`n`nNew List of SuperHeros:"
$SuperHeros

I ran this code and here is the result:

Here are the Super Heros:
Thor
IronMan
AntMan
Hulk
Clint Barton
DeadPool
Captain Marvel
Black Widow


Oops..Black Widow and Clint Barton are not really super heros..Remove them at once.
Yes Sir.


New List of SuperHeros:
Thor   
IronMan
AntMan
Hulk
DeadPool
Captain Marvel

Hope you like this trick. 😉 Leave me a reply!

One thought on “PowerShell Tip: How to remove items from an Array? Yes, it is possible.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s