PowerShell 将 Information 流重定向到 Verbose 流而不写文件
数据小陈
PowerShell 里没有 6>&4 这种把 Information 流直接并入 Verbose 流的可用写法。>& 主要是把指定流合并到 success stream(1),比如 6>&1、2>&1、*>&1。在 PowerShell 7 中,6>&4 会被当成非法重定向,报 “Missing file specification after redirection operator”。
示例里的 Write-Host 会写入 Information 流,但它的默认显示行为不受 $InformationPreference 控制,所以 Attempt 2 不会隐藏 “Host message”。如果希望默认隐藏、加 -Verbose 时显示,可以用一个包装函数:先用 6>&1 把 Information 流捕获到 success 流,再把 InformationRecord 转成 Write-Verbose。调用时只写包装函数,不用写 if/else。
#Requires -Version 7
param(
[switch]$Verbose
)
$VerbosePreference = if ($Verbose) { 'Continue' } else { 'SilentlyContinue' }
function SomeThirdPartyCmdlet {
Write-Host "Host message"
}
function Invoke-InfoAsVerbose {
param(
[Parameter(Mandatory)]
[scriptblock]$ScriptBlock
)
& $ScriptBlock 6>&1 | ForEach-Object {
if ($_ -is [System.Management.Automation.InformationRecord]) {
Write-Verbose -Message ([string]$_.MessageData)
}
else {
$_
}
}
}
Invoke-InfoAsVerbose { SomeThirdPartyCmdlet }
Write-Host "End"
调用时把目标命令放进脚本块即可:
Invoke-InfoAsVerbose { SomeThirdPartyCmdlet -Param1 foo -Param2 bar }
如果目标命令用的是 Write-Information 而不是 Write-Host,可以先试更简单的偏好设置:
$InformationPreference = if ($Verbose) { 'Continue' } else { 'SilentlyContinue' }
SomeThirdPartyCmdlet
不过这段只对受 $InformationPreference 控制的 Information 输出有效,对 Write-Host 这类宿主输出通常无效。
注意事项:
6>&1会把 Information 记录暂时放进 success 流,包装函数必须识别并过滤InformationRecord,否则它们会作为普通对象输出。- 转成
Write-Verbose后,记录类型会从 InformationRecord 变为 VerboseRecord,原始颜色、标签、NoNewline等格式信息可能丢失。 - 如果命令输出大量对象,包装函数会增加一层管道开销;对性能极敏感的场景要实测。
- 只想隐藏 Information 流时,
6> $null仍然是最直接的方式;但如果你要求“隐藏且可在-Verbose时查看”,就需要上面的捕获再转发方案。
备注:内容仅供参考。
