Joe Blow
Joe Blow

Reputation: 11

Variable is not getting updated

I have a very small script that I'm trying to get to run, and test. See below:

$value = Get-Content C:\Temp\cdrc2g.txt

if ($value -ge 3600)
{
    Invoke-Expression C:\Scripts\Email.ps1
}

There's a text file named "cdrc2g.txt" that is getting updated with a numeric value every 15 minutes. I'm trying to run the above in Task Scheduler every hour. When I was doing testing, I'm noticing that $value doesn't update when the file changes. It seems like it grabs the very first number, and never updates.

For example, if I change the cdrc2g.txt file manually to some number higher than 3600, nothing happens. It should email me, but PowerShell isn't seeing the different value. I've confirmed that PowerShell isn't running, and completely closes after Task Scheduler is done. What can I do to get the $value to update every time Task Scheduler runs this script?

Upvotes: 1

Views: 244

Answers (4)

Esperento57
Esperento57

Reputation: 17492

You can use option -wait to get-content command, this option wait when file is modified, use -tail 1 to take last row of your file

gc "C:\Temp\cdrc2g.txt" -Wait -Tail 1  | where { $_ -eq "3600"} | Invoke-Expression C:\Scripts\Email.ps1

Upvotes: 0

Joe Blow
Joe Blow

Reputation: 11

Guys thanks for all the input. The text file would only have one number - representing seconds. A co-worker showed me if I changed my script to include [int] like below:

[int]$value = Get-Content C:\Temp\cdrc2g.txt

if ($value -ge 3600) {Invoke-Expression C:\Scripts\Email.ps1}

My problem went away. I was able to change the value in the text file and re-run my scheduled task, and it worked the way it was supposed to.

Upvotes: 0

DNinjaDave
DNinjaDave

Reputation: 11

Does the value update when you run the script manually?

When you say

I've confirmed that PowerShell isn't running, and completely closes after Task Scheduler is done.

Do you mean that you're expecting PowerShell to remain running once the script completes?

Perhaps you need a loop to keep the script going and re-evaluating the file? somtehing like:

While ($True) {
    $value = Get-Content C:\Temp\cdrc2g.txt

    if ($value -ge 3600) {
        Invoke-Expression C:\Scripts\Email.ps1
    }
    Start-Sleep -Seconds (15*60)
}

Perhaps the script isn't able to read the file from the scheduled task because of permissions or a file lock or something. You could confirm the value is able to be read by scheduling a task like:

Get-Content C:\Temp\cdrc2g.txt | Out-File C:\Temp\test.txt -append

Then check the test.txt file after it runs.

Upvotes: 1

Martin Brandl
Martin Brandl

Reputation: 59021

You are probably looking for the -tail parameter:

$value = Get-Content C:\Temp\cdrc2g.txt -Tail 1

This will always returns the last entry.

Upvotes: 0

Related Questions