Replacing Variable Names in ISE 3.0 Editor

by Jul 2, 2013

If you want to replace variables in a PowerShell script, in PowerShell ISE 3.0 you can use the following function:

function Replace-Variable
{
    param(
      [Parameter(Mandatory=$true)]
      $OldName,

      [Parameter(Mandatory=$true)]
      $NewName
    )

    $token=$null
    $text = $psise.CurrentFile.Editor.Text
    $ast = [System.Management.Automation.Language.Parser]::ParseInput($text, [ref]$token, [ref]$null) 
    $token | ForEach-Object {
        if ($_.Kind -eq 'Variable')
        {
            $_
        }
        elseif ($_.Kind -eq 'StringExpandable')
        {
            $_.NestedTokens
        }
        
    } | 
    Where-Object { $_.Name -eq $OldName } |
    Sort-Object { $_.Extent.StartOffset } -Descending |
    ForEach-Object {
      $psise.CurrentFile.Editor.Select($_.Extent.StartLineNumber, $_.Extent.StartColumnNumber+1, $_.Extent.EndLineNumber, $_.Extent.EndColumnNumber)
      $psise.CurrentFile.Editor.InsertText($NewName)
    }

}

Replace-Variable takes an existing variable name and a new variable name. It then reads the PowerShell script currently displayed in the ISE and replaces all instances of the variable with the new name.

A few things to note: always submit the pure variable name only, and do not include the "$". This call, for example, would replace all instances of $test with $myVariable:

Replace-Variable -OldName test -NewName myVariable

This function also uses the new PowerShell 3.0 parser, so it will not run with PowerShell 2.0. The new parser can find nested variables. So even if a variable was included in a double-quoted string, it will still be replaced.

Twitter This Tip! ReTweet this Tip!