How to run powershell script from python

Question:

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

Asked By: Евгений

||

Answers:

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()
Answered By: Евгений
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.