Search code examples
powershellwindows-scripting

I have a Problem with Powershell writing text to console


This will be easy for most of you answer, but I'm struggling with it. For instance, if I input Get-Tpm, the return I get is, Get-tpm written to console, as shown below.

If I enter

ECHO Get-tpm > C:\dssupport\output.txt

the output is a text file containing 'Get-tpm:'

screenshot

Is there a way to do both, so that I can see it on my monitor, and also saved as a text file?

I'm grateful for any help at all.

Thank you


Solution

  • Most PowerShell cmdlets like Get-Tpm output objects which usually display on the console screen formatted as table or as list. You can easily write output like that to a file, usually a structured Csv file you can open in Excel using Export-Csv.

    That last cmdlet however does not have something neat like a parameter called -PassThru, but what you can do is use a cmdlet that does let you do that.

    In your example, you could do

    # show on screen AND write to CSV file
    Get-Tpm | ConvertTo-Csv -NoTypeInformation | Set-Content -Path 'X:\TPM.csv' -PassThru
    

    or

    # show on screen AND write to JSON file
    Get-Tpm | ConvertTo-Json | Set-Content -Path 'X:\TPM.json' -PassThru
    

    or even

    # show on screen as list AND write to text file
    Get-Tpm | Format-List | Out-String | Set-Content -Path 'X:\TPM.txt' -PassThru
    

    Although a file written like that is not really meant to be used for anything other than display purposes.

    Or you can do this in separate lines of code where you show on screen as list for instance and in the other line write the csv file. For that, you need to capture the results from the cmdlet in a variable:

    $result = Get-Tpm
    # show on screen as list (or table)
    $result | Format-List   # or do Format-Table -AutoSize
    
    # show in a separate grid view window
    $result | Out-GridView -Title "My TPM results"
    
    # output to CSV file
    $result | Export-Csv -Path 'X:\TPM.csv' -NoTypeInformation