Powershell 捕获不同变量中的输出和详细信息 [英] Powershell capture both output and verbose information in different variables

查看:65
本文介绍了Powershell 捕获不同变量中的输出和详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将输出和详细信息都捕获到两个不同的变量中?

Is it posible to capture both output and verbose information into two different variables?

我的要求:

我正在创建一个带有 powershell 和 wpf 的 gui,它有一个仅显示详细和错误的富文本框.

I am creating a gui with powershell and wpf where it has a richtextbox which display only verbose and errors.

例如,如果我执行 get-dscconfiguration -verbose ,详细流应该转到 Richtextbox 并且该 cmdlet 的输出应该分配给一个变量以供进一步操作.

For example if i execute get-dscconfiguration -verbose , verbose stream should go to richtextbox and output of that cmdlet should be asigned to a variable for further manuplation.

请帮助我实现这一目标.谢谢!

Please help me achive this. Thank you!

-vinay

推荐答案

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

You can capture one stream to a variable or multiple streams to a variable but beyond that you will need to send to file and read back in or filter the variable that captured multiple streams. For example to capture only verbose output you can run the command as a subexpression.

$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 中.

When run this outputs the error and warning objects to console but the verbose objects are saved into $VerboseOnly and the output objects are saved into $OutputOnly.

您可以重定向多个流,如下例所示:

You can redirect multiple streams as well as the following example shows:

$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 子句过滤来将它们拉出.

At this point only the error object was written to console, the output System.IO.DirectoryInfo object is in $outputOnly, and the warning and verbose messages are in $VerboseAndWarning. You can then pull them out by filtering with a where-object clause.

$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".

这篇关于Powershell 捕获不同变量中的输出和详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆