Why can't I use predefined variables in class methods?

旧城冷巷雨未停 提交于 2020-12-10 14:20:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!