Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Last active September 6, 2026 22:41
Show Gist options
  • Select an option

  • Save Jaykul/9ce585018dbd3d64f8fab9cc7347a4a2 to your computer and use it in GitHub Desktop.

Select an option

Save Jaykul/9ce585018dbd3d64f8fab9cc7347a4a2 to your computer and use it in GitHub Desktop.
Magic Variables or Automatic Variables

PowerShell automatic variables are predefined variables that return information about the PowerShell environment, the current operation, and recent events. They're called automatic because they're maintained by PowerShell itself and update automatically as you use the shell. A few examples:

  • Error – A list of the most recent errors where $Error[0] is the last error.
  • $MyInvocation – Information about the current script or command, such as the name, parameters and parameter values.
  • $_ – Contains the current object in pipeline input

There are many more. In general, these variables cannot be set or modified directly by the user, and they're useful because they exist automatically and reliably to provide additional execution context in scripts and sessions.

For a complete list, see about_Automatic_Variables.

Interestingly, it's possible to create your own variables that are almost as automatic. That is, it's possible to define additional variables that calculate their value each time they're invoked, and even make them ReadOnly or AllScope, as long as you're careful.

# You can define your own magic or automatic variables in pure PowerShell, by deriving custom classes from PSVariable:
class Uptime : PSVariable {
# You can even have properties that are not part of the variable value
hidden [System.DateTimeOffset]$Created = (get-process -Id $global:pid).StartTime
# You MUST implement the mandatory base constructor
Uptime([string]$Name): base($name) {
# But you can do anything or nothing on initialization
}
# Then you override get_value to (calculate and) return your magic value
[object]get_Value() {
return [System.DateTimeOffset]::Now - $this.Created
}
}
# Finally, initialize one with a name ...
$ExecutionContext.SessionState.PSVariable.Set([Uptime]::new("Up"))
# Now, $Up will show the uptime for this shell process ...
# BE VERY CAREFUL about this though, because taking over variables is perilous.
# For instance, if you made it AllScope,ReadOnly it would block the variable name from use
Set-Variable -Name Up -Option ReadOnly -Scope Global
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment