简体   繁体   English

powershell-如何多次运行代码的特定部分

[英]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? 如果我想多次运行PS脚本,则可以使用Windows Scheduler,但是如果我需要多次运行某些部分代码而不是整个脚本,该怎么办?

I have script to monitor remote server and I need to check processor time every second and the amount of ram every minute. 我有监视远程服务器的脚本,我需要每秒检查处理器时间和每分钟ram的数量。 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 您也许可以为此使用WMI计时器

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 备注 :另一个解决方案是使用Windows Forms计时器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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