0

我有一个脚本,它接受“-outToFilename”作为非强制性参数,如果需要,可以在控制台和文件上都有一个日志。通常我使用这样的功能:

function myLogger {
    [CmdletBinding()] 
    param(
        [Parameter(Mandatory)]
        [string]$myMessage,       
        [Parameter(Mandatory)]
        [string]$logToFile
    )
    if ($logToFile) {
       write-host $myMessage |tee -append -filePath $logToFile
    } else {
       write-host $myMessage
}

但是在玩Tee-Object时,我想知道是否可以有条件地将write-host cmdlet 的输出通过管道传输到 tee-object
像这样:

write-host $myMessage | if ($logToFile) { $_ | tee -filePath $logToFile }<br/>


使用tee-Object进行编辑最好使用write-output,以便 Tee 可以从管道中获取值:
write-output $myMessage | 如果 ($logToFile) { $_ | tee -filePath $logToFile }

同样,在等待更好的解决方案时,当我需要有条件地输出到()控制台和文件时,我正在使用这个:

write-host -ForegroundColor yellow "Some text to show"
if ( $saveToFile) { Write-output  "Some text to show" | tee -FilePath $saveToFile -Append |Out-Null }
4

0 回答 0