52

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Houman
  • 64,245
  • 87
  • 278
  • 460

2 Answers2

55

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.

manojlds
  • 290,304
  • 63
  • 469
  • 417
  • One more thing, could $test be an array or list instead? It would be great to add to a collection when executing a command and at the end I just could loop through the collection and add them to email body? – Houman Dec 07 '11 at 22:47
  • I think you can cast it to an array: [string[]] $test = & $Env:WinDir\system32\inetsrv\appcmd.exe – Andy Arismendi Dec 08 '11 at 06:41
26

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
Gunasekaran
  • 441
  • 5
  • 5