简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM