python - 从 Python 运行 powershell 脚本而无需在每次运行时重新导入模块

标签 python powershell subprocess powershell-2.0

我正在创建一个 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/

相关文章:

python - 嵌套序列化器 Django Rest Framework

python - Python中类的顶级属性存储在哪里

powershell - 'AdditionalDeploymentContributors' 不是 'Publish' 操作的有效参数

Python - 使用子进程调用 sed?

python - 使用 Notepad++ 将每一行保存为单独的 .txt 文件

python - 比较两个文件并将报告保存在任何其他文件中

c# - 将多个 XML 转换为 JSON 列表

powershell - 通过引用访问列表的问题

python - 在子进程 Python 期间记录

python - subprocess.call 在 PyCharm (linux) 中不工作