Powershell – 如何保持跨会话加载导入的模块

我有一堆使用一个普通的PowerShell库(混合自定义PS函数和C#类)的不同脚本。 脚本会定期自动执行。 当每个脚本加载时,它使用相当多的CPU导入自定义模块。 当所有的脚本立即启动服务器的CPU运行在100%…有没有办法导入模块只有一次? 在这种情况下,所有脚本都由Windows服务执行。

Solutions Collecting From Web of "Powershell – 如何保持跨会话加载导入的模块"

如果以相当短的时间间隔运行,那么最好将其加载一次,保持驻留,并将其放入睡眠/进程/睡眠循环中。

您也可以将模块加载到运行空间池中,并将池传递给多个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 ImportPSmoduleesFromPath method may be more appropriate depending on your situation $pool.InitialSessionState.ImportPSmodulee("NameOfYourmodulee") #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({SomeScriptBlockThatRequiresYourmodulee}) #assign the runspacepool $ps.RunspacePool = $pool #begin an asynchronousous 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)