Powershell Write-Host Formating Question RRS feed

  • General discussion

  • I am guessing there is a pretty easy answer to this, but I have not been able to find it.

    I have a script that I need to list data from a variable, but it always outputs the data in columns. Here is an example:

    $CSV = C:\test\ComputerList.csv
    $Computers = Get-content $CSV
    Write-host $computers

    The output displays like:

    Computer1 Computer2 Computer3

    Desired output is:




    I have tried numerous flavors of Format-List but none seem to work. If I replace 'Write-Host $Computers' with simply '$Computers' it lists correctly, but I need to use foreground/backround parameters of Write-Host to alert my team of the output of the script

    Any suggestions?

    • Changed type Bill_Stewart Friday, July 27, 2018 8:16 PM
    • Moved by Bill_Stewart Friday, July 27, 2018 8:16 PM Unanswerable drive-by question
    Friday, April 20, 2018 4:50 PM

All replies

  • Don't use Write-Host. It writes only to the host and is for host output only (can't be redirected).

    -- Bill Stewart [Bill_Stewart]

    Friday, April 20, 2018 5:03 PM
  • Use write output rather than write-host. 

    $CSV = C:\test\ComputerList.csv
    $Computers = Get-content $CSV
    Write-output $computers

    Write-host should only ever be used if you want to display something in the console, but don't want to do anything further with it (Such as send it to file, or manipulate it). 

    The following:

    $csv = get-content C:\test2\Test.csv
    Write-host $csv

    Will output one long line as below

    A1,B1,C1,D1,E1,F1,G1,H1,I1,J1 A2,B2,C2,D2,E2,F2,G2,H2,I2,J2 A3,B3,C3,D3,E3,F3,G3,H3,I3,J3 A4,B4,C4,D4,E4,F4,G4,H4,I4,J4 A5,B5,C5,D5,
    E5,F5,G5,H5,I5,J5 A6,B6,C6,D6,E6,F6,G6,H6,I6,J6 A7,B7,C7,D7,E7,F7,G7,H7,I7,J7 A8,B8,C8,D8,E8,F8,G8,H8,I8,J8 A9,B9,C9,D9,E9,F9,G9,H9,

    Whereas write-output 

    $csv = get-content C:\test2\Test.csv
    Write-output $csv

    Will retain the csv structure:


    Friday, April 20, 2018 8:36 PM
  • You don't even need to use Write-Output. Just put the variable by itself. If you don't do anything to consume its value, PowerShell will output it.

    -- Bill Stewart [Bill_Stewart]

    Friday, April 20, 2018 9:27 PM
  • Try

    $CSV = C:\test\ComputerList.csv
    $Computers = Get-content $CSV
    $Computers | foreach {
      Write-host $_

    Tuesday, May 15, 2018 9:38 AM