Renaming Variables

by Oct 6, 2014

PowerShell ISE 3 and later

Here is a simple variable renaming function that you can use in the built-in ISE editor that ships with PowerShell 3 and later.

It will identify any instance of a variable and then replace it with a new name.

function Rename-Variable
{
  param
  (
    [Parameter(Mandatory=$true)]
    $OldName,
    
    [Parameter(Mandatory=$true)]
    $NewName
  )
  
  $InputText = $psise.CurrentFile.Editor.Text
  $token = $null
  $errors = $null
  
  $ast = [System.Management.Automation.Language.Parser]::ParseInput($InputText, [ref] $token, [ref] $errors)
  
  $token | 
  Where-Object { $_.Kind -eq 'Variable'} | 
  Where-Object { $_.Name -eq $OldName } |
  Sort-Object { $_.Extent.StartOffset } -Descending |
  ForEach-Object {
    $start = $_.Extent.StartOffset + 1
    $end = $_.Extent.EndOffset
    $InputText = $InputText.Remove($start, $end-$start).Insert($start, $NewName)
  }
  
  $psise.CurrentFile.Editor.Text = $InputText
} 

Run the function, and you now have a new command called Rename-Variable.

Next, open a script in the ISE editor, and in the console pane, enter this (and of course, replace the old variable name “oldVariableName” with the name of a variable that actually exists in your currently opened ISE script).


PS> Rename-Variable -OldName oldVariableName -NewName theNEWname

Immediately, all occurrences of the old variable are replaced with the new variable name.

Important: this is a very simple variable renaming function. Always make a backup of your scripts. This is not a production-ready variable refactoring solution.

When you rename variables, there may be other parts of your script that would also need to be updated. For example, when a variable is a function parameter, then all calls to that function would also need to change their parameter name.

Twitter This Tip! ReTweet this Tip!