FRALEWHALE
FRALEWHALE

Reputation: 65

Powershell output to a text file

I am creating a script that pulls all of the date and time information from our servers. The script gets the servers from a text file. I am having is getting the output of a script to be written to a text file.

I tried using a pipe with Out-File like so:

$servers = gc "C:\Users\Public\Shell_NTP\TestList.txt"

foreach ($server in $servers){
$dt = gwmi win32_operatingsystem -computer $server
$dt_str = $dt.converttodatetime($dt.localdatetime)
write-host "$($server) current local time is $($dt_str)" | Out-File 
"C:\Users\Public\Shell_NTP\TestListOutput.txt"

Then I tried the simple carrot output like so:

$servers = gc "C:\Users\Public\Shell_NTP\TestList.txt"

foreach ($server in $servers){
$dt = gwmi win32_operatingsystem -computer $server
$dt_str = $dt.converttodatetime($dt.localdatetime)
write-host "$($server) current local time is $($dt_str)" > 
C:\Users\Public\Shell_NTP\TestListOutput.txt

And that did not work either. So any help or advice would be excellent.

TL;DR Trying to get the powershell output into a text file or some other more usable file format.

Upvotes: 1

Views: 21118

Answers (2)

TessellatingHeckler
TessellatingHeckler

Reputation: 29033

You don't need to use write-output you can just

"text" | Out-File ...

into a text file or some other more usable file format

CSV is a more usable format. The format you're writing is something you will have to process again to get the data back out of the text. CSV you can just Import-Csv to get it back. Or open in Excel, etc.

gc "C:\Users\Public\Shell_NTP\TestList.txt" | ForEach {

    $dt = gwmi win32_operatingsystem -Computer $_

    [PSCustomObject]@{
        'ServerName' = $_
        'DateTime' = $dt.converttodatetime($dt.localdatetime)
    }

} | Export-Csv C:\Users\Public\Shell_NTP\TestListOutput.csv -NoTypeInformation

Upvotes: 1

zdan
zdan

Reputation: 29460

Don't use write-host - use write-output

write-host will only output your string to the console, the data will not be passed along the pipleline.

Upvotes: 2

Related Questions