运行Powershell脚本INSIDE python脚本

问题描述 投票:0回答:1

我正在尝试在python脚本中运行Powershell脚本。我的想法是做类似的事情:

#pythonscript.py


def windowsupdate():

    #Somehow call all of this powershell code within the file

    Write-Host("Installing module PSWindowsUpdate if not already installed... ")
    Install-Module PSWindowsUpdate
    Write-Host("PSWindowsUpdate is now installed.")
    Write-Host("")
    Write-Host("Getting Windows Updates...")
    Import-Module PSWindowsUpdate
    $updates = Invoke-Command -ScriptBlock {Get-Wulist -verbose}
    $updatenumber = ($updates.kb).count
    if ($null -ne $updates){
        Get-WindowsUpdate -AcceptAll -Install | Out-File C:\PSWindowsUpdate.log
        do {$updatestatus = Get-Content c:\PSWindowsUpdate.log
            "Currently processing the following update:"
            Get-Content c:\PSWindowsUpdate.log | select-object -last 1
            Start-Sleep -Seconds 10
            $ErrorActionPreference = 'SilentlyContinue'
            $installednumber = ([regex]::Matches($updatestatus, "Installed" )).count
            $ErrorActionPreference = ‘Continue’
        }until ( $installednumber -eq $updatenumber)
    }
    Remove-Item -path C:\PSWindowsUpdate.log


#call function
windowsupdate() #opens up a powershell window and goes through the code then when completed close

如果有任何方法可以执行与此类似的操作,而无需创建单独的powershell文件,那将是最好的情况。如果不是这样,并且也需要将其保存在自己的文件中,并且如果需要这样,我该如何在python中调用该函数?

非常感谢您的帮助!

python-3.x function powershell
1个回答
0
投票

以下代码应该可以工作,尽管我没有对其进行测试:

def windowsupdate():
    pscommand = ' Write-Host("Installing module PSWindowsUpdate if not already installed... ")
    Install-Module PSWindowsUpdate
    Write-Host("PSWindowsUpdate is now installed.")
    Write-Host("")
    Write-Host("Getting Windows Updates...")
    Import-Module PSWindowsUpdate
    $updates = Invoke-Command -ScriptBlock {Get-Wulist -verbose}
    $updatenumber = ($updates.kb).count
    if ($null -ne $updates){
        Get-WindowsUpdate -AcceptAll -Install | Out-File C:\PSWindowsUpdate.log
        do {$updatestatus = Get-Content c:\PSWindowsUpdate.log
            "Currently processing the following update:"
            Get-Content c:\PSWindowsUpdate.log | select-object -last 1
            Start-Sleep -Seconds 10
            $ErrorActionPreference = 'SilentlyContinue'
            $installednumber = ([regex]::Matches($updatestatus, "Installed" )).count
            $ErrorActionPreference = ‘Continue’
        }until ( $installednumber -eq $updatenumber)
    }
    Remove-Item -path C:\PSWindowsUpdate.log'

    import subprocess;
    process=subprocess.Popen(["powershell","& {" + pscommand + "}"],stdout=subprocess.PIPE);
    result=process.communicate()[0]
    print (result)

windowsupdate()
© www.soinside.com 2019 - 2024. All rights reserved.