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

Luk*_*e D 4 python powershell subprocess powershell-2.0

我正在创建一个Python脚本,该脚本调用script.ps1需要导入Active-Directory模块的Powershell脚本.但是,每次运行powershell脚本时 check_output('powershell.exe -File script.ps1') ,都需要为每次运行的script.ps1重新导入活动目录模块,这使得运行时间大约需要3秒.

我当时想知道,如果有办法保持导入Powershell模块(好像是直接从Powershell运行,而不是从Python运行),这样我就可以使用像

if(-not(Get-Module -name ActiveDirectory)){
  Import-Module ActiveDirectory
}
Run Code Online (Sandbox Code Playgroud)

加快执行时间.

bri*_*ist 5

此解决方案使用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
Run Code Online (Sandbox Code Playgroud)

它利用PowerShell对断开连接的会话的支持.每次弹出PowerShell.exe时,最终都会连接到已加载ActiveDirectory模块的现有会话.

完成所有调用后,您应该销毁会话:

Get-PSSession -ComputerName . | Remove-PSSession
Run Code Online (Sandbox Code Playgroud)

这是在每次运行时使用单独的powershell.exe调用进行测试的.

我确实想知道延迟的原因是否真的是因为加载了ActiveDirectory模块,或者至少很大一部分延迟是由于必须加载PowerShell.exe本身造成的.