问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/40935058/why-cant-i-use-predefined-variables-in-class-methods