Error: Variable is not assigned in the method: Unterschied zwischen den Versionen

Aus Wiki-WebPerfect
Wechseln zu: Navigation, Suche
(Die Seite wurde neu angelegt: „You are writing a own PowerShell class and get the following error "Variable is not assigned in the method". -> Here is the solution for this. == Error== '''V…“)
(kein Unterschied)

Version vom 16. August 2021, 09:31 Uhr

You are writing a own PowerShell class and get the following error "Variable is not assigned in the method". -> Here is the solution for this.

Error

Variable is not assigned in the method.


Cause

This error occurs because you are using a predefinied variable in a class method and the class method is in a different scope.


Example to reproduce the error

Ungültige Sprache.

Die gewünschte Sprache muss wie folgt definiert werden: <source lang="html4strict">...</source>

Unterstützte Sprachen für die Syntaxhervorhebung:

 [Ausklappen


Class CustomFunction {
    [String]$Version

    GetVersion() {
        If ($PSVersionTable) {
            $this.Version = $PSVersionTable.PSVersion
        }
    }
}

$CustomFunction = [CustomFunction]::new()
$CustomFunction.GetVersion()
Write-Host $CustomFunction.Version


Solution

  • Add the Scope to your variable ($GLOBAL:<YOUR_VARIABLE>)

Here the solution for the example above:

Ungültige Sprache.

Die gewünschte Sprache muss wie folgt definiert werden: <source lang="html4strict">...</source>

Unterstützte Sprachen für die Syntaxhervorhebung:

 [Ausklappen


Class CustomFunction {
    [String]$Version

    GetVersion() {
        If ($GLOBAL:PSVersionTable) {
            $this.Version = $GLOBAL:PSVersionTable.PSVersion
        }
    }
}

$CustomFunction = [CustomFunction]::new()
$CustomFunction.GetVersion()
Write-Host $CustomFunction.Version