Search code examples
powershellconsoleoutput-redirect

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

Solution

  • 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.