Getting a Variable Inventory

by Oct 7, 2014

PowerShell ISE 3 and later

For documentation purposes, you may want to get a list of all variables that a PowerShell script uses.

Here is a function called Get-Variable:

function Get-Variable
  $token = $null
  $errors = $null
  $ast = [System.Management.Automation.Language.Parser]::ParseInput($psise.CurrentFile.Editor.Text, [ref] $token, [ref] $errors)
  # not complete, add variables you want to exclude from the list:
  $systemVariables = '_', 'null', 'psitem', 'true', 'false', 'args', 'host'
  $null = $ast.FindAll({ $args[0] -is [System.Management.Automation.Language.CommandAst] }, $true)
  $token | 
    Where-Object { $_.Kind -eq 'Variable'} |
    Select-Object -ExpandProperty Name |
    Where-Object { $systemVariables -notcontains $_ } |
    Sort-Object -Unique

Simply load a script into the built-in ISE editor, then from the interactive console, run Get-Variable.

You will get a sorted list of all variables used by the currently opened script.

If you replace $psise.CurrentFile.Editor.Text” by a variable that contains script code, you can run this function outside the ISE editor, as well. Simply use Get-Content to load the contents of any script into a variable, and then use this variable in place of the code above.

Twitter This Tip! ReTweet this Tip!