0

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

2 Answers2

0

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()
  • Now i have an error: PSSecurityException, FullyQualifiedErrorId : UnauthorizedAccess p.s. I can run my script without python, i have all access And can run my .ps1 file succesfully – Евгений Jul 21 '22 at 07:39
  • I found this [answer](https://superuser.com/a/106363) that might help. Start Windows PowerShell with the "Run as Administrator" option. Enable running unsigned scripts by entering: `set-executionpolicy remotesigned` This will allow running unsigned scripts that you write on your local computer and signed scripts from Internet. – Sezai Burak Kantarcı Jul 21 '22 at 08:02
  • Maybe you can try this in your python script aswell: `p = subprocess.Popen('powershell.exe -ExecutionPolicy RemoteSigned -file "your_script_path"', stdout=sys.stdout)` – Sezai Burak Kantarcı Jul 21 '22 at 08:05
0
import subprocess, sys

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