How to Replace Values in an Array in PowerShell (2024)

Do you need to replace or update values in a PowerShell array? In this PowerShell tutorial, we’ll explore how to replace values in an array in PowerShell using different methods with examples.

To replace values in an array in PowerShell, you can use a ForEach-Object loop or the -replace operator. For example, $array = $array | ForEach-Object { $_ -replace ‘oldValue’, ‘newValue’ } will replace all occurrences of ‘oldValue’ with ‘newValue’ in the array. If the array contains simple strings and you want to replace a specific value, you can directly set the value using an index, like $array[0] = ‘newValue’ if you want to replace the first element.

Table of Contents

Replace Values in an Array in PowerShell

Here is an example of an array in PowerShell.

$myArray = 1, 2, 3, 4, 5

Now, let’s say you want to replace a value in the above array in PowerShell. There are several methods to do this, and we’ll cover each one with examples.

1. Using Index Assignment

The simplest way to replace an item in an array in PowerShell is by using its index. Arrays are zero-indexed, which means the first item has an index of 0, the second item an index of 1, and so on. Here’s how you can replace the second item (value 2) with a new value (10):

$myArray = 1, 2, 3, 4, 5$myArray[1] = 10

You can see here below that after I executed the PowerShell script using VS code, the 2nd item (index – 1) was replaced with the value 10.

How to Replace Values in an Array in PowerShell (1)

2. Using the -replace Operator

PowerShell also provides the -replace operator, which can be used to replace specific text or characters in an array. This is useful when you want to replace parts of string values. For example:

$myArray = "cat", "bat", "rat"$myArray = $myArray -replace 'at','oy'$myArray

After this operation, $myArray will contain “coy”, “boy”, “roy”.

3. Using a Loop to Replace Values

Sometimes, you might need to replace values based on a condition. In such cases, a loop can be handy. For example, replacing all instances of the number 2 with the number 20. Here is the complete PowerShell script to replace a value in an array using a for loop.

$myArray = 1, 2, 3, 4, 5, 2for ($i = 0; $i -lt $myArray.Length; $i++) { if ($myArray[$i] -eq 2) { $myArray[$i] = 20 }}$myArray

Once you execute the PowerShell script, it will display the output like in the screenshot below:

How to Replace Values in an Array in PowerShell (2)

4. Using the ForEach-Object Cmdlet

The ForEach-Object cmdlet is a more PowerShell-idiomatic way of performing the same action as a loop. Here’s how you can use it to replace values in an array in PowerShell.

$myArray = 1, 2, 3, 4, 5, 2$myArray = $myArray | ForEach-Object { if ($_ -eq 2) { 20 } else { $_ }}$myArray

5. Using a Custom Function

For more complex scenarios or frequent array value replacements, you might want to define a custom function; here, you can see that I wrote a custom function that will take two parameters (old value, new value) and finally it will replace the new value with the old value in the PowerShell array.

function Replace-ArrayValue { param( [array]$Array, [object]$OldValue, [object]$NewValue ) for ($i = 0; $i -lt $Array.Length; $i++) { if ($Array[$i] -eq $OldValue) { $Array[$i] = $NewValue } } return $Array}# Usage$myArray = Replace-ArrayValue -Array $myArray -OldValue 2 -NewValue 20

This function takes an array and replaces all occurrences of $OldValue with $NewValue.

Conclusion

Replacing values in an array is a common task in PowerShell scripting. Whether you’re using index assignment, the -replace operator, loops, the ForEach-Object cmdlet, or a custom function, PowerShell provides the flexibility to update your arrays effectively.

In this PowerShell tutorial, I have explained the below different ways to replace values in an array in PowerShell with examples.

  1. Using Index Assignment
  2. Using the -replace Operator
  3. Using a Loop to Replace Values
  4. Using the ForEach-Object Cmdlet
  5. Using a Custom Function

You may also like:

  • How to Pick Random Items from an Array in PowerShell?
  • How to Find Duplicates in an Array in PowerShell?
  • How to Remove Blank Lines from an Array in PowerShell?
  • How to Join an Array into a String in PowerShell?
  • Expand Array in PowerShell

How to Replace Values in an Array in PowerShell (3)

Bijay Kumar

Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.

How to Replace Values in an Array in PowerShell (2024)
Top Articles
The Sims Cheats
45 Lakh Home Loan EMI and Interest Rate for 10, 20 and 30 Years
Fighter Torso Ornament Kit
How To Fix Epson Printer Error Code 0x9e
Aberration Surface Entrances
Rondale Moore Or Gabe Davis
Wild Smile Stapleton
True Statement About A Crown Dependency Crossword
Lost Pizza Nutrition
A Fashion Lover's Guide To Copenhagen
Knaben Pirate Download
Capitulo 2B Answers Page 40
Https://Gw.mybeacon.its.state.nc.us/App
Signs Of a Troubled TIPM
Scholarships | New Mexico State University
Citymd West 146Th Urgent Care - Nyc Photos
Discover Westchester's Top Towns — And What Makes Them So Unique
About Us | TQL Careers
Painting Jobs Craigslist
Paradise leaked: An analysis of offshore data leaks
Carolina Aguilar Facebook
Missed Connections Inland Empire
Www.publicsurplus.com Motor Pool
Program Logistics and Property Manager - Baghdad, Iraq
Morristown Daily Record Obituary
Air Quality Index Endicott Ny
Rochester Ny Missed Connections
Spiritual Meaning Of Snake Tattoo: Healing And Rebirth!
4 Times Rihanna Showed Solidarity for Social Movements Around the World
'Insidious: The Red Door': Release Date, Cast, Trailer, and What to Expect
Doctors of Optometry - Westchester Mall | Trusted Eye Doctors in White Plains, NY
Craigslist Comes Clean: No More 'Adult Services,' Ever
Jailfunds Send Message
49S Results Coral
91 Octane Gas Prices Near Me
Publix Coral Way And 147
Solarmovie Ma
Ourhotwifes
Texters Wish You Were Here
Craigslist Hamilton Al
Rocketpult Infinite Fuel
Family Fare Ad Allendale Mi
Solemn Behavior Antonym
Raising Canes Franchise Cost
Myanswers Com Abc Resources
Questions answered? Ducks say so in rivalry rout
Az Unblocked Games: Complete with ease | airSlate SignNow
UT Announces Physician Assistant Medicine Program
Borat: An Iconic Character Who Became More than Just a Film
Searsport Maine Tide Chart
Conan Exiles Colored Crystal
Theatervoorstellingen in Nieuwegein, het complete aanbod.
Latest Posts
Article information

Author: The Hon. Margery Christiansen

Last Updated:

Views: 6116

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.