C# Powershell-如何跨会话加载导入的模块

C# Powershell-如何跨会话加载导入的模块,c#,windows,powershell,C#,Windows,Powershell,我有一系列使用通用Powershell库的不同脚本(自定义PS函数和c#类的混合)。脚本会定期自动执行。当加载每个脚本时,它将使用相当多的CPU来导入自定义模块。当所有脚本同时启动时,服务器的CPU将以100%的速度运行。。。 有没有办法只导入一次模块? 在这种情况下,所有脚本都由Windows服务执行。如果它以相当短的时间间隔运行,最好将其加载一次,使其保持驻留状态,并将其放入睡眠/进程/睡眠循环。您还可以将模块加载一次到runspacepool中,并将该池传递给powershell的多个实例

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

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

您还可以将模块加载一次到runspacepool中,并将该池传递给powershell的多个实例。有关更多详细信息,请参阅和类。样本:

#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)