You're probably looking for this:
class MyObject {
[string] $gamarjoba = '' # instance variable
# Method has no return type; accepts a string parameter
# and assigns it to instance variable $this.gamarjoba
[void] SetString([string] $gamarjoba) {
$this.gamarjoba = $gamarjoba
}
# Returns the uppercased form of the $this.gamarjoba instance variable.
# Do NOT use Write-Host.
[string] PrintString() {
return $this.gamarjoba.ToUpper()
}
}
$obj = [MyObject]::new() # create an instance
$obj.SetString('aha') # set the string
$obj.PrintString() # print the uppercased string
Note that I've named the class MyObject
, because Object
would clash with the root class of the .NET type hierarchy.
As for what you tried:
return Write-Host "gamarjoba".ToUpper()
Fundamentally, do NOT use Write-Host
to return or output data - it is meant for printing information to the display (console), and bypasses the success output stream and thereby the ability to send output to other commands, capture it in a variable, or redirect it to a file - see this answer for more information.
In the context of class
definitions, use only return
to return data from a method, passing it an expression or command as-is (e.g, return 'foo'.ToUpper()
or return Get-Date -Format yyy
)
PowerShell class
es participate in the system of output streams only in a very limited way:
return
ing a value from a method writes it to the success output stream.
- Notably, implicit output and use of
Write-Output
(i.e. what you would use in a script or function) are not supported and quietly ignored. (While you can use return Write-Output ...
, there's no good reason to do so.)
throw
ing an error writes it to the error stream - but you'll only see that if you catch or silence such a fatal-by-default error.
- Notably, using
Write-Error
to write non-terminating errors does not work and is quietly ignored.
However, you can write to all other output streams using their respective Write-*
cmdlets, such as Write-Warning
.