Error: Variable is not assigned in the method: Unterschied zwischen den Versionen
Aus Wiki-WebPerfect
Admin (Diskussion | Beiträge) (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…“) |
Admin (Diskussion | Beiträge) |
||
(3 dazwischenliegende Versionen des gleichen Benutzers werden nicht angezeigt) | |||
Zeile 10: | Zeile 10: | ||
== Example to reproduce the error == | == Example to reproduce the error == | ||
− | <source lang="powershell> | + | <source lang="powershell"> |
− | Class | + | Class CustomClass { |
[String]$Version | [String]$Version | ||
Zeile 21: | Zeile 21: | ||
} | } | ||
− | $ | + | $CustomClass = [CustomClass]::new() |
− | $ | + | $CustomClass.GetVersion() |
− | Write-Host $ | + | Write-Host $CustomClass.Version |
</source> | </source> | ||
== Solution == | == Solution == | ||
− | *Add the Scope to your variable ($GLOBAL:<YOUR_VARIABLE>) | + | *Add the Scope to your variable ('''$GLOBAL:'''<YOUR_VARIABLE>) |
'''Here the solution for the example above:''' | '''Here the solution for the example above:''' | ||
− | <source lang="powershell> | + | <source lang="powershell"> |
− | Class | + | Class CustomClass { |
[String]$Version | [String]$Version | ||
Zeile 41: | Zeile 41: | ||
} | } | ||
− | $ | + | $CustomClass = [CustomClass]::new() |
− | $ | + | $CustomClass.GetVersion() |
− | Write-Host $ | + | Write-Host $CustomClass.Version |
</source> | </source> | ||
Aktuelle Version vom 16. August 2021, 13:27 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.
Inhaltsverzeichnis
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
Class CustomClass { [String]$Version GetVersion() { If ($PSVersionTable) { $this.Version = $PSVersionTable.PSVersion } } } $CustomClass = [CustomClass]::new() $CustomClass.GetVersion() Write-Host $CustomClass.Version
Solution
- Add the Scope to your variable ($GLOBAL:<YOUR_VARIABLE>)
Here the solution for the example above:
Class CustomClass { [String]$Version GetVersion() { If ($GLOBAL:PSVersionTable) { $this.Version = $GLOBAL:PSVersionTable.PSVersion } } } $CustomClass = [CustomClass]::new() $CustomClass.GetVersion() Write-Host $CustomClass.Version