Search code examples
powershellverbose

Powershell Standard Verbose to a variable


I've written a script that is like this, I use the $output1 in order to redirect the output of the standard verbose.

$output1 = $(
    cmdlet1 [Some Parameters] -Verbose | % {
        cmdlet2 [Other Some Parameters] -Verbose
    } ) 4>&1

When I do not store the standard verbose in a variable, it prints in the powershell in a good way, with newline. But When I capture the standard verbose in the $output1and save it in a file, it prints everything in one very long single line.

How can I store in my variable the standard verbose in a good way?


Solution

  • As far as I know there is no easy syntax for this. Why? Because pipeline output would otherwise interfere with verbose, warning and error messages. There is still workaround, little more complex. Redirect your verbose output to temporary file, get content, remove file. Take a look:

    $resultFile = [System.IO.Path]::GetTempFileName();
    1| % {
        $x = [System.IO.Path]::GetTempFileName();
        rm $x -Verbose
    } 4>$resultFile
    $result = cat $resultFile
    rm $resultFile
    

    In your example:

    $resultFile = [System.IO.Path]::GetTempFileName();
    $(
    cmdlet1 [Some Parameters] -Verbose | % {
        cmdlet2 [Other Some Parameters] -Verbose
    }) 4>&1
    $output1 = cat $resultFile
    rm $resultFile