AvoidUsingWriteHost

嚴重性層級:警告

描述

此規則偵測不使用Show動詞的函式中的用Write-Host法。 Write-Host設計用於在主機中產生僅顯示的輸出,例如列印彩色文字或提示使用者輸入。Read-Host 它使用該 ToString() 方法來寫入輸出,結果取決於 PowerShell 主機程式。

由於 Write-Host 不會將輸出傳送到管線,你需要 Write-Output 或隱含的輸出來將資料傳遞到管線。

除非使用Show動詞,否則避免使用 Write-Host 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
}

Compliant

針對參考訊息使用 Write-Verbose。 用戶可以藉由提供 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'
}