pat
pat

Reputation:

Powershell - refresh date in variable

My question is, how can I store date in variable, and then push there new date. I'll explain my code: -get today's date and substract it from last write time of file -get amount of hours -while last write time is greater or equal 1 hour inform to edit file -get most recent last write time -then sleep 10 seconds

The problem is that even if I edit file, loop still shows previous date. How can I make it work?

$file = get-childitem $input_users
   $time = (get-date)-$file.lastwritetime
   $hours = $time.hours

   while (($time.hours) -ge (1)){
         write-host -BackgroundColor DarkRed -ForegroundColor White  "$input was written to $hours hours ago, please edit it first"
         write-host -BackgroundColor DarkRed -ForegroundColor White  "Next check in 10 seconds."
         $time = (get-date)-$file.lastwritetime
                                }  

Upvotes: 1

Views: 1097

Answers (1)

EBGreen
EBGreen

Reputation: 37720

You need to get a new file object and recalculate the hours inside the loop:

$file = get-childitem $input_users
$time = (get-date)-$file.lastwritetime
$hours = $time.hours

while (($time.hours) -ge (1)){
    write-host -BackgroundColor DarkRed -ForegroundColor White  "$input was written to $hours hours ago, please edit it first"
    write-host -BackgroundColor DarkRed -ForegroundColor White  "Next check in 10 seconds."
    $file = Get-ChildItem $input_users
    $time = (Get-Date) - $file.LastWriteTime

}

Upvotes: 1

Related Questions