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
What is an Asset? What is a Liability?
MarinePoland.com
Public Opinion Obituaries Chambersburg Pa
Tlc Africa Deaths 2021
Dannys U Pull - Self-Service Automotive Recycling
Overton Funeral Home Waterloo Iowa
Busted Newspaper Zapata Tx
What spices do Germans cook with?
Txtvrfy Sheridan Wy
Sprague Brook Park Camping Reservations
Mail Healthcare Uiowa
THE 10 BEST River Retreats for 2024/2025
Devourer Of Gods Resprite
The Many Faces of the Craigslist Killer
Miss America Voy Forum
Grace Caroline Deepfake
Unit 33 Quiz Listening Comprehension
"Une héroïne" : les funérailles de Rebecca Cheptegei, athlète olympique immolée par son compagnon | TF1 INFO
Canvas Nthurston
Gemita Alvarez Desnuda
Craigslist Portland Oregon Motorcycles
Alfie Liebel
Tyrone Unblocked Games Bitlife
Poe Str Stacking
Jc Green Obits
Best Sports Bars In Schaumburg Il
Troy Gamefarm Prices
Shoe Station Store Locator
Pdx Weather Noaa
Warren County Skyward
60 Second Burger Run Unblocked
Newsday Brains Only
Montrose Colorado Sheriff's Department
2008 Chevrolet Corvette for sale - Houston, TX - craigslist
Trap Candy Strain Leafly
Cranston Sewer Tax
How Many Dogs Can You Have in Idaho | GetJerry.com
Tyler Perry Marriage Counselor Play 123Movies
Registrar Lls
sacramento for sale by owner "boats" - craigslist
Jetblue 1919
Traumasoft Butler
Chase Bank Zip Code
Honkai Star Rail Aha Stuffed Toy
20 Mr. Miyagi Inspirational Quotes For Wisdom
Jimmy John's Near Me Open
Join MileSplit to get access to the latest news, films, and events!
Craigslist Sarasota Free Stuff
The 5 Types of Intimacy Every Healthy Relationship Needs | All Points North
Uno Grade Scale
Billings City Landfill Hours
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.