powershell - How to update variables in script? -


script should restart service , save current data , time in file after memory usage reach limit. doesn't save current time , in second if when service stopped doesn't else. show same values in $data , $stat. not sure 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 } 

the statements in variable assignments evaluated @ time of assignment, not when variable used. latter define statements scriptblocks:

$data = { get-date -format 'yyyy\/mm\/dd hh:mm:ss' } $stat = { get-process mysqld -ea silentlycontinue } 

use call operator (&) in expression (()) or subexpression ($()) evaluate scriptblocks @ later point in script:

if ((&$stat) -ne $null) {     add-content -path $log -value "working" } else {     start-service $serv     add-content -path $log -value "$(&$data)`tstarting" } 

probably more convenient way define operations 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 this:

if (test-mysqlprocess) {     add-content -path $log -value "working" } else {     start-service $serv     add-content -path $log -value "$(get-timestamp)`tstarting" } 

as side note, should escape forward slashes in date format strings, otherwise windows substitutes them whatever date separator character configured in system's regional settings.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -