Skip to content

Many PowerShell Automatic Variables are not available to custom class methods #12915

@IarwainBen-adar

Description

@IarwainBen-adar

Steps to reproduce

class FooClass { FooClass() { Write-Host $HOME } }

Expected behavior

I would have expected that class objects would be able to read all PowerShell Automatic Variables as if they were globals.

Actual behavior

ParserError:
Line |
   1 |  class FooClass { FooClass() { Write-Host $HOME } }
     |                                           ~~~~~
     | Variable is not assigned in the method.

Interestingly, this works:

function Get-Home { return $HOME }
class FooClass { FooClass() { Write-Host $(Get-Home) } }

I assume this is a similar/related issue to #9174, but for tracking purposes (in e.g. #6652) it seems like it would be useful to have an issue for the general case. I went through the list and it seems that the following Automatic Variables are not available within class methods:

$$
$^
$ConsoleFileName
$Event
$EventArgs
$EventSubscriber
$ExecutionContext
$HOST
$IsCoreCLR
$IsLinux
$IsMacOS
$IsWindows
$PID
$PROFILE
$PSCulture
$PSDebugContext
$PSHOME
$PSUICulture
$PSVersionTable
$Sender
$ShellId

Whereas these Automatic Variables are available within class methods:

$?
$_
$args
$Error
$false
$foreach
$input
$LastExitCode
$Matches
$MyInvocation
$NestedPromptLevel
$null
$PSBoundParameters
$PSCmdlet
$PSCommandPath
$PSItem
$PSScriptRoot
$PWD
$StackTrace
$switch
$this
$true

Environment data

Name                           Value
----                           -----
PSVersion                      7.0.1
PSEdition                      Core
GitCommitId                    7.0.1
OS                             Microsoft Windows 10.0.18363
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-No ActivityIssue has had no activity for 6 months or moreWG-Enginecore PowerShell engine, interpreter, and runtime

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions