Finding Built-In Variables Part 2

by Feb 22, 2013

In a previous tip we featured a piece of undocumented code that works in PowerShell v3 to list all built-in variables. Here is another approach that also works in PowerShell v2. It creates a fresh new runspace and dumps all variables. Since the runspace had no chance to define user variables, you just get predefined PowerShell variables:

PS> [powershell]::create().addcommand('Get-Variable').invoke() | Select-Object -ExpandProperty Name

So again, we can turn this into a function called Get-MyVariable which lists only your own variables. Like with the other approach, it is still necessary to hard-code a small number of built-in variables.

function Get-MyVariable
{
    $builtin = [powershell]::create().addcommand('Get-Variable').invoke() | Select-Object -ExpandProperty Name
    $builtin += 'args','MyInvocation','profile', 'PSBoundParameters', 'PSCommandPath', 'psISE', 'PSScriptRoot', 'psUnsupportedConsoleApplications'

    Get-Variable |
      Where-Object { $builtin -NotContains $_.Name } |
      Select-Object -Property Name, Value, Description
}

Twitter This Tip! ReTweet this Tip!