Powershell -如何保持导入模块跨会话加载
本文关键字:会话 加载 模块 导入 何保持 Powershell | 更新日期: 2023-09-27 18:08:02
我有一堆不同的脚本使用一个通用的Powershell库(自定义PS函数和c#类的混合)。脚本会定期自动执行。当每个脚本加载时,它会使用相当多的CPU来导入自定义模块。当所有脚本同时启动时,服务器的CPU以100%的速度运行……有没有一种方法可以只导入模块一次?在此场景中,所有脚本都由Windows服务执行。
您还可以将模块加载一次到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)
如果它以相当短的间隔运行,那么您最好加载它一次,让它驻留,并将其放入sleep/process/sleep循环中。