txjastx
txjastx

Reputation: 11

powershell get-date to log file

I'm trying to get a script to test connectivity of a list of IP addresses and log the output to a file. I would like it to put a time/date stamp in the log when when I get no response. I'd like to execute the script over a 2-3 day period. I've got it to put the time/date stamp on the output of the console but not in the output file. Here's the script.

$names=Get-Content "C:\script\hname.txt"
foreach($name in $names){
    if(Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
        Write-Host "$name is up" -ForegroundColor Green
        $output+="$name is up,"
    }
    else{
        Write-Host "$name is down" -ForegroundColor Red
        Get-Date 
        $output+="$name is down,"
        " "
    }
}
$output | Out-File -FilePath "C:\script\results.txt"
Start-Sleep -s 3

this is the results on the ps console

PS C:\Windows\system32> C:\Users\admin\Documents\Test Connection-3sec.ps1
192.168.1.254 is up
192.168.1.74 is down

Tuesday, October 10, 2023 12:06:05 PM
 
192.168.1.239 is up
192.168.1.23 is down
Tuesday, October 10, 2023 12:06:07 PM
 
192.168.1.189 is up
192.168.1.78 is up
192.168.1.79 is up
192.168.1.81 is up
192.168.1.89 is down
Tuesday, October 10, 2023 12:06:08 PM
 
192.168.1.82 is up
192.168.1.85 is up
192.168.1.45 is down
Tuesday, October 10, 2023 12:06:10 PM

PS C:\Windows\system32> 

But this is what I get in the results.txt file.

192.168.1.254 is up,
192.168.1.74 is down,
192.168.1.239 is up,
192.168.1.23 is down,
192.168.1.189 is up,
192.168.1.78 is up,
192.168.1.79 is up,
192.168.1.81 is up,
192.168.1.89 is down,
192.168.1.82 is up,
192.168.1.85 is up,
192.168.1.45 is down,

as a side note the format doesn't have the new line feed which I understand I should be able to get if I add $output+="$name is up," +"`n`r"

I've tried putting the get-date at the end of the $output line, to no avail.

$output+="$name is down," Get-Date

How can I do this?

Upvotes: 1

Views: 171

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 416131

To match the console output:

$output+="$name is down,`n$(Get-date)`n"

But personally I'd simplify it and keep the date on the same line

$output+="$name is down. $(Get-date)"

And of course you could always add it to $output as its own entry:

$output+="$name is down, "
$output+= Get-date

Upvotes: 1

Related Questions