Search code examples
powershellpowershell-2.0powershell-remoting

powershell - how to run specific part of code several times


if I want to run PS script several times, I can use windows scheduler, but what if I need to run several times certain part of code, not whole script?

I have script to monitor remote server and I need to check processor time every second and the amount of ram every minute. I don't want to split it to more separate scripts, because I'm monitoring dozens of values. Or do you have some different idea of resolvint that?

Thank you!


Solution

  • You perhaps can use WMI timer for that

    PS C:\> $iClsTimer = [wmiclass]"__IntervalTimerInstruction"
    PS C:\> $iTimer = $iClsTimer.CreateInstance();
    PS C:\> $iTimer.TimerId="MonEvtTimer"
    PS C:\> $iTimer.IntervalBetweenEvents= 2000
    PS C:\> $iTimer.SkipIfPassed=$true
    PS C:\> $iTimer.Put()
    
    Path          : \\.\root\cimv2:__IntervalTimerInstruction.TimerId="MonEvtTimer"
    RelativePath  : __IntervalTimerInstruction.TimerId="MonEvtTimer"
    Server        : .
    NamespacePath : root\cimv2
    ClassName     : __IntervalTimerInstruction
    IsClass       : False
    IsInstance    : True
    IsSingleton   : False
    
    PS C:\silogix> $query = "Select * From __TimerEvent Where TimerID='MonEvtTimer'"
    PS C:\silogix> Register-WMIEvent -Query $query -Action {write-host "Timer"}
    
    Id              Name            State      HasMoreData     Location       Command
    --              ----            -----      -----------     --------       -------
    2               19e70483-2a0... NotStarted False                          write-host "Timer"
    

    Remark : Another solution is to use Windows Forms timer