有没有可能将输出和详细信息分别捕获到两个不同的变量中?
我正在使用PowerShell和WPF创建一个GUI,其中有一个richtextbox仅显示详细和错误信息。
例如,如果我执行以下操作:
get-dscconfiguration -verbose
然后详细的流应该进入richtextbox,该cmdlet的输出应该被分配给一个变量以进行进一步的操作。
有没有可能将输出和详细信息分别捕获到两个不同的变量中?
我正在使用PowerShell和WPF创建一个GUI,其中有一个richtextbox仅显示详细和错误信息。
例如,如果我执行以下操作:
get-dscconfiguration -verbose
然后详细的流应该进入richtextbox,该cmdlet的输出应该被分配给一个变量以进行进一步的操作。
您可以将一个流捕获到变量中,也可以将多个流捕获到变量中,但是除此之外,您需要发送到文件并读取回来或过滤捕获了多个流的变量。例如,要仅捕获详细输出,您可以将命令作为子表达式运行。
$VerboseOnly = $($OutputOnly= .{
New-Item -ItemType Directory -Path c:\Test -Verbose
Remove-Item -Path c:\Test -Verbose
Remove-Item -Path c:\Test -Verbose
Write-Warning "warning"
}) 4>&1
$VerboseAndWarning = $(
$OutputOnly = .{
New-Item -ItemType Directory -Path c:\Test -Verbose
Remove-Item -Path c:\Test -Verbose
Remove-Item -Path c:\Test -Verbose
Write-Warning "warning"
}) 4>&13>&1
此时只有错误对象被写入控制台,输出的System.IO.DirectoryInfo对象在$outputOnly中,警告和详细信息在$VerboseAndWarning中。然后您可以通过使用where-object子句进行过滤来提取它们。
$VerboseAndWarning | Where-Object {$_ -is [System.Management.Automation.WarningRecord]}
WARNING: warning
$VerboseAndWarning | Where-Object {$_ -is [System.Management.Automation.VerboseRecord]}
VERBOSE: Performing operation "Create directory" on Target "Destination: C:\Test".
VERBOSE: Performing operation "Remove Directory" on Target "C:\Test".
使用Where-Object
(别名为符号?
)是一种显而易见的方法,但有点过于繁琐。它需要大量的代码。
这样做不仅需要更长的时间,还会增加错误的概率。
实际上,在PowerShell中有一种更简洁的方法,可以将不同的流分别分配给不同的变量(这个方法是我偶然发现的)。
# First, declare a method that outputs both streams at the same time.
function thisFunc {
[cmdletbinding()]
param()
Write-Output 'Output'
Write-Verbose 'Verbose'
}
# The separation is done in a single statement.Our goal has been achieved.
$VerboseStream = (thisFunc -Verbose | Tee-Object -Variable 'String' | Out-Null) 4>&1
然后我们验证这两个变量的内容
$VerboseStream.getType().FullName
$String.getType().FullName
以下信息应出现在控制台上:
PS> System.Management.Automation.VerboseRecord
System.String
4>&1
' 表示将 verboseStream 重定向到 success stream,然后可以将其保存到变量中,当然您可以将此数字更改为介于2和5之间的任何数字。 如果您觉得我的方法不错,请点击鼠标为我投票,非常感谢。这段内容与编程有关。https://dev59.com/pWAf5IYBdhLWcg3w2Fl6#33002914
上述URL是对另一个类似问题的答案,很可能会对您有所帮助。
他同时输入了stdout和stderr,然后在完成后将它们分开。但这不是即时完成的。
您可以简单地将每个变量保存到自己的变量中。