AvoidUsingWriteHost

严重性级别:警告

默认状态:始终启用

描述

该规则用于检测不使用Write-Host动词的函数中的用Show法。 Write-Host设计用于在主机中产生仅显示的输出,比如打印彩色文本或提示用户输入。Read-Host 它使用该 ToString() 方法写入输出,结果取决于 PowerShell 主机程序。

由于 Write-Host 不会将输出发送到流水线,你需要 Write-Output 或隐含的输出来传递数据。

除非使用Write-Host动词,否则避免使用 Show in,动词明确表示向用户显示信息。 此规则不适用于具有 Show 谓词的函数。

根据你的意图,将 写-主机 替换为写- 输出写-冗长 。 用于 Write-Verbose 日志记录和 Write-Output 返回物品。

非符合性

function Get-MeaningOfLife
{
    Write-Host 'Computing the answer to the ultimate question of life, the universe and everything'
    Write-Host 42
}

合规的

Write-Verbose 用于信息性消息。 用户可以通过提供 详细 参数来确定是否查看消息。

function Get-MeaningOfLife {
    [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
}

function Show-Something {
    Write-Host 'Show something on screen'
}

配置规则

这个规则始终是启用的,不能配置。 请采用以下方法之一以避免使用此规则:

  • 创建一个自定义规则配置文件,只包含你想要的规则,或者排除你不想要的规则。
  • 在代码中添加相应的规则抑制属性,以抑制特定代码块的规则。 更多信息请参见使用 PSScriptAnalyzer 中的“抑制规则”部分。