简体   繁体   中英

Running powershell scripts from Python without reimporting modules on every run

I am creating a Python script that calls a Powershell script script.ps1 that needs to import the Active-Directory module. However, every time I run the powershell script using check_output('powershell.exe -File script.ps1') it needs to re-import the active directory module for each run of script.ps1, which makes the run time take about 3 seconds longer then it needs to.

I was wondering then, if there was a way to keep the Powershell module imported (as if it were being ran directly from Powershell, and not from Python) so that I can use things like

if(-not(Get-Module -name ActiveDirectory)){
  Import-Module ActiveDirectory
}

to speed up execution time.

This solution uses PowerShell remoting, and requires that the machine you remote into has the ActiveDirectory module, and it requires that the machine making the remote connection (the client) be PowerShell version 3 or higher.

In this example, the machine remotes into itself.

This would be your script.ps1 file:

#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

It takes advantage of PowerShell's support for disconnected sessions. Each time you shell out to PowerShell.exe, you end up connecting to an existing session with the ActiveDirectory module already loaded.

Once you're done with all the calls, you should destroy the session:

Get-PSSession -ComputerName . | Remove-PSSession

This was tested with a separate powershell.exe invocation on every run.

I do wonder if the cause for your delays is actually because of loading the ActiveDirectory module though, or if at least a significant portion of the delays are caused merely by having to load PowerShell.exe itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM