wpf Powershell在不同的变量中捕获输出和详细信息[重复]

wlwcrazw  于 2023-01-10  发布在  Shell
关注(0)|答案(3)|浏览(159)
    • 此问题在此处已有答案**:

Capture program stdout and stderr to separate variables(7个答案)
2天前关闭。
是否可以将输出和详细信息捕获到两个不同的变量中?
我正在用powershell和wpf创建一个图形用户界面,其中有一个只显示详细信息和错误的richtextbox。
例如,如果我执行以下命令:

get-dscconfiguration -verbose

然后,详细流应转到richtextbox,并且该cmdlet的输出应分配给一个变量以供进一步操作。

jbose2ul

jbose2ul1#

您可以将一个流捕获到一个变量,也可以将多个流捕获到一个变量,但除此之外,您将需要发送到文件并回读或筛选捕获多个流的变量。例如,要仅捕获详细输出,您可以将命令作为子表达式运行。

$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

运行时,此命令将错误和警告对象输出到控制台,但详细对象保存到$VerboseOnly,输出对象保存到$OutputOnly。
您可以重定向多个流,如下例所示:

$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

此时,只有error对象被写入控制台,输出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".
xdnvmnnf

xdnvmnnf2#

使用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流,然后可以将其保存到变量中,当然您可以将此数字更改为2到5之间的任何数字。

如果你觉得和我的方法还不错,请点击鼠标投我一票,非常感谢。

eqqqjvef

eqqqjvef3#

https://stackoverflow.com/a/33002914
上面的URL是对另一个类似问题的回答,很可能会对您有所帮助。
他同时为stdout和stderr提供数据,然后在完成后将它们拆分,但这不是动态完成的。
您可以简单地将每个变量保存到其自己的变量中。

相关问题