Running powershell scripts from Python without re-passing modules every time you start

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

Then I was wondering if there was a way to import the Powershell module (as if it were running directly from Powershell, not Python), so that I could use things like

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

to speed up runtime.

+4
source share
1 answer

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 . , PowerShell.exe, ActiveDirectory.

, :

Get-PSSession -ComputerName . | Remove-PSSession

powershell.exe .

, ActiveDirectory, PowerShell.exe.

+5

Source: https://habr.com/ru/post/1598971/


All Articles