- What can I do so that I write the desired phrase in brackets and it will be accepted?
- Where exactly to get the "basis" in order to make a return using the "PrintString" method?
# Example 1
$Object.SetString("gamarjoba")
# Example 2
$Object.PrintString()
# Returns
GAMARJOBA
Here is one of my attempts:
class Object {
[string]$gamarjoba
[string]SetString() {
return Write-Host "gamarjoba"
}
[string]PrintString() {
return Write-Host "gamarjoba".ToUpper()
}
}
I understand that this is a very basic question, but I have already spent too much time on it.
CodePudding user response:
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 onlyreturn
to return data from a method, passing it an expression or command as-is (e.g,return 'foo'.ToUpper()
orreturn 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 usereturn Write-Output ...
, there's no good reason to do so.)
- Notably, implicit output and use of
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.
- Notably, using
However, you can write to all other output streams using their respective
Write-*
cmdlets, such asWrite-Warning
.