Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide a reason for this rule #276

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
description: Avoid Using Write-Host
ms.date: 06/28/2023
ms.date: 12/05/2024
ms.topic: reference
title: AvoidUsingWriteHost
---
Expand All @@ -10,10 +10,15 @@ title: AvoidUsingWriteHost

## Description

The use of `Write-Host` is greatly discouraged unless in the use of commands with the `Show` verb.
The `Show` verb explicitly means 'show on the screen, with no other possibilities'.
The primary purpose of the `Write-Host` cmdlet is to produce display-only output in the host. For
example: printing colored text or prompting the user for input when combined with `Read-Host`.
`Write-Host` uses the `ToString()` method to write the output. The particular result depends on the
program that's hosting PowerShell. The output from `Write-Host` isn't sent to the pipeline. To
output data to the pipeline, use `Write-Output` or implicit output.

Commands with the `Show` verb do not have this check applied.
The use of `Write-Host` in a function is discouraged unless the function uses the `Show` verb. The
`Show` verb explicitly means _display information to the user_. This rule doesn't apply to functions
with the `Show` verb.

## How

Expand All @@ -27,22 +32,22 @@ logging or returning one or more objects.
```powershell
function Get-MeaningOfLife
{
...
Write-Host 'Computing the answer to the ultimate question of life, the universe and everything'
...
Write-Host 42
}
```

### Correct

Use `Write-Verbose` for informational messages. The user can decide whether to see the message by
providing the **Verbose** parameter.

```powershell
function Get-MeaningOfLife
{
[CmdletBinding()]Param() # to make it possible to set the VerbosePreference when calling the function
...
[CmdletBinding()]Param() # makes it possible to support Verbose output

Write-Verbose 'Computing the answer to the ultimate question of life, the universe and everything'
...
Write-Output 42
}

Expand All @@ -51,3 +56,7 @@ function Show-Something
Write-Host 'show something on screen'
}
```

## More information

[Write-Host](xref:Microsoft.PowerShell.Utility.Write-Host)