简体   繁体   中英

How to run powershell script from python

how i can run my PS script from Python?

$StartDate = (Get-Date).adddays(-1).tostring("dd/MM/yyyy",$LocaleRU) 
$Machine = "name"
$Events = Get-WinEvent -FilterHashtable @{Logname = "ForwardedEvents"; ID = 4740; StartTime=$StartDate;}  -ComputerName $Machine # -MaxEvents 5

    foreach ($event in $Events)
        {
        [xml]$Xml = $event.ToXml()
        $login=$xml.Event.EventData.Data.'#text'[0]
        $hostName = $xml.Event.EventData.Data.'#text'[1]
        write-host "$login;$hostName"
        }

I try to use subprocess.call(["powershell.exe", ....]) but i dont know how i need to paste my script here. Thanks

Just like you said, using subprocess might help here. With the help of this answer:

Save your PS script in a .ps1 file on your machine and do something like:

import subprocess, sys

# An example script path = C:\\Users\\USER\\Desktop\\my_script.ps1
# Also adding the execution policy in order to avoid Security exception error

p = subprocess.Popen('powershell.exe -ExecutionPolicy RemoteSigned -file "your_script_path"', stdout=sys.stdout)

p.communicate()
import subprocess, sys

p = subprocess.Popen('powershell.exe -ExecutionPolicy RemoteSigned -file "PowerShell1.ps1"', stdout=sys.stdout)
p.communicate()

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