Auto-Documenting Script Variables

by Apr 9, 2013

PowerShell can automatically find and list all variables that you use in a script. This way, you can easily create variable documentation for your scripts (and also find variables that may be misspelled):

Function Get-ISEVariable
{
  $text = $psISE.CurrentFile.Editor.Text

  [System.Management.Automation.PSParser]::Tokenize($text, [ref]$null) |
  Where-Object { $_.Type -eq 'Variable' } |
  ForEach-Object {
    $rv = 1 | Select-Object -Property Line, Name, Code
    $rv.Name = $text.Substring($_.Start, $_.Length)
    $rv.Line = $_.StartLine

    $psISE.CurrentFile.Editor.SetCaretPosition($_.StartLine,1)
    $psISE.CurrentFile.Editor.SelectCaretLine()
    $rv.Code = $psISE.CurrentFile.Editor.SelectedText.Trim()

    $rv
  }
}

When you run Get-ISEVariable in your ISE editor, you get a dump of all variables found in the currently opened script:

To get a list of all variables used in your script, try this:

You can even document how often a variable was used:

Twitter This Tip! ReTweet this Tip!