I'm trying to start a PowerShell script from python like this:
psxmlgen = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
'./buildxml.ps1',
arg1, arg2, arg3], cwd=os.getcwd())
result = psxmlgen.wait()
The problem is that I get the following error:
File C:\Users\sztomi\workspace\myproject\buildxml.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
DESPITE the fact that I did enable running scripts in Powershell a long time ago by typing Set-ExecutionPolicy Unrestriced
in an administrator-ran PS terminal (and did again, just to make sure). The powershell executable is the same that the shortcut in start menu points to. Get-ExecutionPolicy
correctly reports Unrestricted
no matter if I ran PowerShell as admin or not.
How can I execute a PS script correctly from Python?
It's possible to run PowerShell from within python using subprocess. run() and specifying the powershell.exe path.
Bring together the Python programming language and Microsoft's PowerShell to address digital investigations and create state-of-the-art solutions for administrators, IT personnel, cyber response teams, and forensic investigators.
How do you pass arguments to a PowerShell script in Python? To pass arguments verbatim to the PowerShell CLI, use the -File option: pass the script-file path first, followed by the arguments to pass to the script.
In File Explorer (or Windows Explorer), right-click the script file name and then select "Run with PowerShell". The "Run with PowerShell" feature starts a PowerShell session that has an execution policy of Bypass, runs the script, and closes the session.
First, Set-ExecutionPolicy Unrestriced
is on a per user basis, and a per bitness basis (32-bit is different than 64-bit).
Second, you can override the execution policy from the command line.
psxmlgen = subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
'-ExecutionPolicy',
'Unrestricted',
'./buildxml.ps1',
arg1, arg2, arg3], cwd=os.getcwd())
result = psxmlgen.wait()
Apparently you can access the 64-bit PowerShell from 32-bit PowerShell with this path (thanks to @eryksun in comments):
powershell64 = os.path.join(os.environ['SystemRoot'],
'SysNative' if platform.architecture()[0] == '32bit' else 'System32',
'WindowsPowerShell', 'v1.0', 'powershell.exe')
For those of us who wanted to know how to display the values of arg1, arg2 and arg3 after it was passed to powershell, all you need to do is:
Write-Host $args[0]
Write-Host $args[1]
Write-Host $args[2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With