String manipulation is a common activity for any PowerShell scripter. I deal with strings all the time and unfortunately they aren't always in quite the right format as I'd like to find. Using the replace() method is a great way to either remove or simply replace snippets of text you'd like to change inside strings.

Let's take an example of renaming headers in a CSV file.

In this situation I was given a CSV file from an HR software system. This software exported the list of employees with the following headers. The left is what the HR software exported and the right is how I needed the column name to actually show up as.

  • EMPLOYEE - Employee ID
  • LAST_NAME - Last Name
  • FIRST_NAME - First Name
  • R_NAME - Department
  • MIDDLE_INIT - Middle Initial
  • HR_EMSTATUS - Hire Status

As you can see I have no idea how it came up with some of these column names but I wasn't having it. In this instance, using PowerShell's replace() method is the perfect solution. The replace() method is a great way to do an essential find and replace on a piece of text in a string. Here's what I did in this instance.

## Read the contents of the export file into a variable
$FileContent = Get-Content hr_system_export.csv

## Create a hash table of key/value pairs of what we want to find and what we want to replace it with
$FindReplace = @{
    'EMPLOYEE'     ='Employee ID'
    'LAST_NAME'     ='Last Name'
    'FIRST_NAME'    ='Fist Name'
    'R_NAME'        ='Department'
    'MIDDLE_INIT'   ='Middle Initial'
    'HR_PAPOSITION' ='Title'
    'HR_EMSTATUS'   ='Hire Status'

## Capture the header row into a variable
$HeaderRow = $FileContent[0]

## Loop through the hash table and find/replace all of the column names
$FindReplace.GetEnumerator() | ForEach-Object {
    $HeaderRow = $HeaderRow.Replace("$($_.Name)","$($_.Value)")

$FindReplace.GetEnumerator() | ForEach-Object {$HeaderRow = $HeaderRow.Replace("$($_.Name)","$($_.Value)")}

## Replace the initial header row in the CSV with our new header row
Set-Content hr_system_export.csv -Value $HeaderRow,$FileContent[1..($FileContent.Count)]

This is just one example of the PowerShell replace() method. You can also dive into the more advanced replace operator if you'd like if you feeling frisky with some regex. That topic is for another day.