Renaming Script Variables

by Apr 12, 2013

Often, when you start writing a PowerShell script, you use temporary (dirty) variable names that later you'd like to polish. Renaming script variables by find/replace is not a very good idea, though, because searching for text can find text inside of strings, commands or other variable names, and potentially wrecks your entire script.

A much better approach uses the built-in PowerShell 3.0 parser:

Function Rename-ISEVariable


  $OldName = $OldName.TrimStart('$')
  $NewName = $NewName.TrimStart('$')

  $text = $psISE.CurrentFile.Editor.Text

  $sb = New-Object System.Text.StringBuilder $text

  $variables = [System.Management.Automation.PSParser]::Tokenize($text, [ref]$null) |
  Where-Object { $_.Type -eq 'Variable' } |
  Sort-Object -Property Start -Descending |
  Where-Object {
    $text.Substring($_.Start+1, $_.Length-1) -eq $OldName
  } |
  ForEach-Object {
    $sb.Remove($_.Start+1, $_.Length-1)
    $sb.Insert($_.Start+1, $NewName)

  $psISE.CurrentFile.Editor.Text = $sb.toString()

Rename-ISEVariable lets you easily and safely rename variables in your scripts:

As you can see, you can replace variables with completely new names, or just change casing. Thanks to the parser, Rename-ISEVariable will change only the variable names you were after. It will not touch strings, commands or other variable names that just contain the text you are looking for.

To run this code from a PowerShell console, you have to load the WPF assemblies first:

Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase

This step is not required inside of the ISE editor because ISE loads these assemblies automatically.

Twitter This Tip! ReTweet this Tip!