Search code examples
powershelloutputstore

Store command with multi line output to variable or file in Powershell


I am trying to store a command prompt command to a variable in Powershell, as well as outputting it to a file. Since the command has 3 lines of output, nothing gets stored as a variable or written to file. The only thing that happens when I attempt to store or output to file, is that the output gets printed to the screen.

input:

java -version

output:

java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b25)
Java HotSpot(TM) Client VM (build 25.251-b25, mixed mode)

I have tried the following which did not work:

$variable = (java -version)
$variable = cmd /c "java -version")
java -version | out-file test.txt

output only prints to screen


Solution

  • Looks like I misread your question, original answer at the bottom

    java.exe likely outputs the version info to the standard error stream, so you'll have to redirect it into the standard output stream first:

    $version = java -version 2>&1
    

    But since PowerShell will attempt to wrap the output from the error stream in ErrorRecord's, we need to convert those back to strings again:

    $version = java -version 2>&1 |ForEach-Object ToString
    

    To learn more about the different output streams in PowerShell and how to redirect them, see the about_Redirection help topic


    Either store the command and arguments in string variables, then invoke with &:

    $command = 'java'
    $arguments = '-version'
    # ... later in the script:
    $javaVersion = & $command $arguments
    

    Alternatively create a scriptblock with the command expression:

    $javaVersionCommand = {
      java -version
    }
    # ... later in the script:
    $javaVersion = & $javaVersionCommand