Search code examples
powershellclasspowershell-5.0powershell-v5.1

Why does Write-Output not work inside a PowerShell class method?


I am trying to output variables using Write-Output, but it did not work inside a PowerShell class method. Write-Host is working. See the sample code below.

class sample {
  [string] sampleMethod() {
    $output = "Output message"
    try {
      Write-Output $output
      throw "error"
    }
    catch {
      Write-Output $output
      $_
    }
    return "err"
  }
}    

$obj = [sample]::new()
$obj.sampleMethod()

Is there any specific reason why Write-Output doesn't work inside a class method?


Solution

  • From the docs:

    In class methods, no objects get sent to the pipeline except those mentioned in the return statement. There's no accidental output to the pipeline from the code.

    This is fundamentally different from how PowerShell functions handle output, where everything goes to the pipeline.

    If you need output just for debugging or whatever, you can use Write-Host, Write-Warning etc., which basically just write to the console.