Powershell - 如何保持跨会话加载导入的模块 [英] Powershell - how to keep imported modules loaded across sessions

查看:28
本文介绍了Powershell - 如何保持跨会话加载导入的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a bunch of different scripts using a common Powershell library (mix of custom PS functions and c# classes). The scripts are executed automatically at a regular intervals. When each script is loading it is using quite a bit of CPU to import the custom modules. When all scripts fire up at once a server's CPU runs at 100%... Is there a way to import-modules only once? In this scenario all scripts are executed by a Windows service.

推荐答案

您还可以将模块一次加载到运行空间池中,然后将该池传递给 powershell 的多个实例.有关更多详细信息,请参阅 InitialSessionStateRunspacePool 类.示例:

You could also load the module once into a runspacepool and pass the pool around to multiple instances of powershell. For more details see the InitialSessionState and RunspacePool classes. Sample:

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

这篇关于Powershell - 如何保持跨会话加载导入的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆