Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture output in a variable rather than a logfile?

Tags:

powershell

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 
like image 382
Houman Avatar asked Dec 07 '11 22:12

Houman


People also ask

How do I redirect output to a File in PowerShell?

There are two PowerShell operators you can use to redirect output: > and >> . The > operator is equivalent to Out-File while >> is equivalent to Out-File -Append . The redirection operators have other uses like redirecting error or verbose output streams.

How do I pipe a PowerShell output to a text File?

To send a PowerShell command's output to the Out-File cmdlet, use the pipeline. Alternatively, you can store data in a variable and use the InputObject parameter to pass data to the Out-File cmdlet. Out-File saves data to a file but it does not produce any output objects to the pipeline.

What are the cmdlets that can send the output to different File formats?

The Out-File cmdlet is most useful when you want to save output as it would have displayed on the console. For finer control over output format, you need more advanced tools.


2 Answers

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.

like image 158
manojlds Avatar answered Sep 30 '22 18:09

manojlds


Capturing the output of a executable is as simple as,

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

2>&1 - Includes the error stream in the output

Return type of the executable in PowerShell is an array of strings. 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 
like image 21
Gunasekaran Avatar answered Sep 30 '22 19:09

Gunasekaran