我有一堆使用常见Powershell库的不同脚本(自定义PS函数和c#类的混合)。脚本定期自动执行。当每个脚本加载时,它使用相当多的CPU来导入自定义模块。当所有脚本立即启动时,服务器的CPU以100%运行... 有没有办法只导入一次模块? 在这种情况下,所有脚本都由Windows服务执行。
答案 0 :(得分:1)
如果它以相当短的间隔运行,你最好将它加载一次,让它保持驻留状态,并将其置于睡眠/进程/睡眠循环中。
答案 1 :(得分:1)
您还可以将模块一次加载到runspacepool中,并将池传递给powershell的多个实例。有关详细信息,请参阅InitialSessionState和RunspacePool类。样品:
#create a default sessionstate
$iss = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
#create a runspace pool with 10 threads and the initialsessionstate we created, adjust as needed
$pool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(1, 10, $iss, $Host)
#Import the module - This method takes a string array if you need multiple modules
#The ImportPSModulesFromPath method may be more appropriate depending on your situation
$pool.InitialSessionState.ImportPSModule("NameOfYourModule")
#the module(s) will be loaded once when the runspacepool is loaded
$pool.Open()
#create a powershell instance
$ps= [System.Management.Automation.PowerShell]::Create()
#Add a scriptblock - See http://msdn.microsoft.com/en-us/library/system.management.automation.powershell_members%28v=vs.85%29.aspx
# for other methods for parameters,arguments etc.
$ps.AddScript({SomeScriptBlockThatRequiresYourModule})
#assign the runspacepool
$ps.RunspacePool = $pool
#begin an asynchronous invoke - See http://msdn.microsoft.com/en-us/library/system.management.automation.powershell_members%28v=vs.85%29.aspx
$iar = $ps.BeginInvoke()
#wait for script to complete - you should probably implement a timeout here as well
do{Start-Sleep -Milliseconds 250}while(-not $iar.IsCompleted)
#get results
$ps.EndInvoke($iar)