Beeen
Beeen

Reputation: 13

How to update variables in script?

Script should restart service and save current data and time in file after memory usage reach the limit. But it doesn't save current time and in second if when service is stopped it doesn't do else. It always show the same values in $data and $stat. I am not sure where I made mistake.

$proc = 'process name'
$serv = 'service name*'
$ram = 10MB
$inter = 1
$data = Get-Date -format "yyyy/MM/dd HH:mm:ss"
$log = "c:\log.txt"
$stat = Get-Process $proc -EA SilentlyContinue

while ($true) {
    if ((Get-Process $proc -EA SilentlyContinue | Select-Object -Exp ws) -gt $ram) {
        Restart-Service $serv
        Add-Content -path $log -value ($data + "`t" + "Restarting")
        Start-Sleep -m 10000
        if ($stat -ne $null) {
            Add-Content -path $log -value "Working"
        } else {
            Start-Service $serv
            Add-Content -path $log -value ($data + "`t" + "Starting")
        }
    }

    Start-Sleep -s $inter
}

Upvotes: 1

Views: 88

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200283

The statements in your variable assignments are evaluated at the time of assignment, not when the variable is used. To get the latter you could define the statements as scriptblocks:

$data = { Get-Date -format 'yyyy\/MM\/dd HH:mm:ss' }
$stat = { Get-Process mysqld -ea SilentlyContinue }

Use the call operator (&) in an expression (()) or subexpression ($()) to evaluate the scriptblocks at a later point in your script:

if ((&$stat) -ne $null) {
    Add-Content -Path $log -Value "Working"
} else {
    Start-Service $serv
    Add-Content -Path $log -Value "$(&$data)`tStarting"
}

Probably a more convenient way is to define the operations as functions:

function Get-Timestamp { Get-Date -format 'yyyy\/MM\/dd HH:mm:ss' }
function Test-MySQLProcess { [bool](Get-Process mysqld -EA SilentlyContinue) }

and use them like this:

if (Test-MySQLProcess) {
    Add-Content -Path $log -Value "Working"
} else {
    Start-Service $serv
    Add-Content -Path $log -Value "$(Get-Timestamp)`tStarting"
}

As a side note, you should escape forward slashes in date format strings, otherwise Windows substitutes them with whatever date separator character is configured in your system's regional settings.

Upvotes: 3

Related Questions