7

I tried to use predefined variables like $PSVersionTable or $PSScriptRoot in a class method. They failed with the error message

Variable is not assigned in the method.

Example:

Class Foo { [String]$Version GetVersion() { If ($PSVersionTable) { $this.Version = $PSVersionTable.PSVersion } } } 

But why?

0

1 Answer 1

15
Class Foo { [String] $Version GetVersion() { if ($global:PSVersionTable) { $this.Version = $global:PSVersionTable.PSVersion } } } $foo = [Foo]::new() $foo.GetVersion() Write-Host $foo.Version 

For the "why" part, I guess this is related to scope. In your class you have to specify in some way that you refer to the global $PSVersionTable variable, and not to something in the class or script scope.

Sign up to request clarification or add additional context in comments.

1 Comment

I keep forgetting this $global 'thang'... thanks David!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.