1

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.