user206168
user206168

Reputation: 1025

How to set global variable and

I have this script running every half hour. It sends an email if the value is greater than 99, but I don't want it to send an email every 30 min if value is still 99.

I would only like it to send an email once. if the value goes back less than 99 then again greater than 99 then send an email once only.

Here is the script

$main = 100


IF ($main -gt 99) {
 Write-Host $main
 ##Send Email
}
else 
{
 Write-Host "Not Greater than 99." 
}

What I tried, it doesn't work.
I tried using a global variable and setting equal nothing if $var1 -eq "NOTSENT" -and $main -gt 99 it will send email and set $var1 = "SENT". I need help here.

$main = 100
$var1 

IF (($main -gt 99) -and ($var1 -eq "NOTSENT")) {
 Write-Host $main
 ##Send Email
 $var1 = "SENT"
}
else 
{
 Write-Host "Not Greater than 99." 
 $var1 = "NOTSENT"
}

Upvotes: 0

Views: 635

Answers (2)

briantist
briantist

Reputation: 47802

mjolinor is correct about the reason it's not working; I won't restate that.

But rather than write to disk, you could set a user level or machine level environment variable instead:

[Environment]::SetEnvironmentVariable('Variable', 'Value' , 'User')
[Environment]::SetEnvironmentVariable('Variable', 'Value' , 'Machine') # requires elevation

See http://technet.microsoft.com/en-us/library/ff730964.aspx

Upvotes: 2

mjolinor
mjolinor

Reputation: 68273

"Global" only means it's global to the PS session it was created in. When the session ends, the variable is gone. If you need to persist that value from one session to another, you need to write it out to disk, and then read it back the next time the script runs.

Upvotes: 2

Related Questions