我正在创建一个 Python 脚本,它调用需要导入 Active-Directory 模块的 Powershell 脚本 script.ps1
。但是,每次我使用运行 powershell 脚本时
check_output('powershell.exe -File script.ps1')
它需要为每次运行 script.ps1 重新导入事件目录模块,这使得运行时间比它需要的时间长大约 3 秒。
当时我在想,是否有办法保持 Powershell 模块的导入(就好像它直接从 Powershell 运行,而不是从 Python 运行),这样我就可以使用类似的东西
if(-not(Get-Module -name ActiveDirectory)){
Import-Module ActiveDirectory
}
加快执行时间。
最佳答案
此解决方案使用 PowerShell 远程处理,并要求您远程进入的计算机具有 ActiveDirectory 模块,并且要求进行远程连接的计算机(客户端)是 PowerShell 版本 3 或更高版本。
在这个例子中,机器远程进入它自己。
这将是您的 script.ps1 文件:
#requires -Version 3.0
$ExistingSession = Get-PSSession -ComputerName . | Select-Object -First 1
if ($ExistingSession) {
Write-Verbose "Using existing session" -Verbose
$ExistingSession | Connect-PSSession | Out-Null
} else {
Write-Verbose "Creating new session." -Verbose
$ExistingSession = New-PSSession -ComputerName . -ErrorAction Stop
Invoke-Command -Session $ExistingSession -ScriptBlock { Import-Module ActiveDirectory }
}
Invoke-Command -Session $ExistingSession -ScriptBlock {
# do all your stuff here
}
$ExistingSession | Disconnect-PSSession | Out-Null
它利用 PowerShell 对断开连接的 session 的支持。每次执行 PowerShell.exe 时,您最终都会连接到已加载 ActiveDirectory 模块的现有 session 。
完成所有调用后,您应该销毁 session :
Get-PSSession -ComputerName . | Remove-PSSession
这是在每次运行时使用单独的 powershell.exe 调用进行测试的。
我确实想知道您延迟的原因是否实际上是因为加载 ActiveDirectory 模块,或者是否至少有很大一部分延迟仅仅是由于必须加载 PowerShell.exe 本身造成的。
关于python - 从 Python 运行 powershell 脚本而无需在每次运行时重新导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31550169/