简体   繁体   English

如何捕获变量而不是日志文件中的输出?

[英]How to capture output in a variable rather than a logfile?

This would write the output to a logfile: 这会将输出写入日志文件:

& $Env:WinDir\system32\inetsrv\appcmd.exe >test.log

But what if I wanted to keep the output in a string variable to use it in the email body? 但是,如果我想将输出保留在字符串变量中以在电子邮件正文中使用该怎么办?

I tried this without any luck.. 我没有运气就尝试了..

$test = ""
& $Env:WinDir\system32\inetsrv\appcmd.exe >$test

Write-Host $test

You have to do: 你所要做的:

$test = & $Env:WinDir\system32\inetsrv\appcmd.exe

If you wanted to redirect error as well, add 2>&1 in the end. 如果您还想重定向错误,请在末尾添加2>&1

Capturing the output of a executable is as simple as, 捕获可执行文件的输出非常简单,

$cmdOutput = &"Application.exe" 2>&1

2>&1 - Includes the error stream in the output 2>&1-在输出中包括错误流

Return type of the executable in PowerShell is an array of strings . PowerShell中可执行文件的返回类型是一个字符串数组 In case of logging such outputs, 如果记录此类输出,

Write-Host $cmdOutput

will output the strings in the array to the output stream separated by spaces 将数组中的字符串输出到以空格分隔的输出流

To print them in a string per line fashion, choose 要以每行的字符串形式打印它们,请选择

Write-Output $cmdOutput

or 要么

$cmdOutput = &"Application.exe" | Out-String
Write-Host $cmdOutput

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM