강병우
강병우

Reputation: 1

powershell Save text in out-file

$timeFromFile = Get-Content 'D:\script2\IIS\timeln.txt'

$diff = [datetime]::Now - [datetime]$timeFromFile

[System.Math]::Round($diff.TotalSeconds)

if ($diff.TotalSeconds -gt 900){
Write-Host "Time difference is greater than 900 seconds"
}   
$diff.TotalSeconds | Out-File 'D:\script2\IIS\EndTime.txt'

When the above script is executed, the result value for the calculated time is saved as EndTime.txt. However, when 900 seconds have passed, the message is not saved in the EndTime.txt file, only the time value is output. How to fix?

Upvotes: 0

Views: 5577

Answers (1)

Karolina Ochlik
Karolina Ochlik

Reputation: 938

Based on the comment "When the above script is executed, the result is only numbers ex) 39568.2052459 Do not record "Time difference is greater than 900 seconds" I finally might have an idea on what you're after :)

What you have done is piped the seconds to file ($diff.TotalSeconds | Out-File 'D:\script2\IIS\EndTime.txt') and you need to pipe the message itself. I added the seconds value in message.

$timeFromFile = [datetime]::Now

$diff = [datetime]::Now - [datetime]$timeFromFile

$diffSecs = [System.Math]::Round($diff.TotalSeconds)

#Initialize empty string variable for message
$msg = ""
if ($diffSecs -gt 900) {
    #Setting the message if greater than 900
    $msg = "Time difference is greater than 900 seconds ($diffSecs)"
}
else {
    #If lower or equal
    $msg = "Time difference IS NOT greater than 900 seconds ($diffSecs)"
}

#Setting the content of file to the $msg variable value
$msg | Out-File C:\Temp\asd.txt

Upvotes: 1

Related Questions