2

I am currently trying to run a simple hello world program in powershell using this code :

import subprocess
import sys

p = subprocess.Popen(["powershell.exe",
                 'C:/users/m.m/Desktop/hello.ps1'],
                 stdout = sys.stdout)
p.communicate()

what i'm trying to do is this; i have saved the "hello.ps1" python program with powershell extension containing print("hello, world!") in desktop and I want to create a program that reads the file within my python files , opens them and runs those scripts in powershell after invoking python by python command.

I have already tried the code above as suggested in here ==> Running powershell script within python script, how to make python print the powershell output while it is running, but it gives me security error.

This is the error that i get when run the code above:

C:/users/m.m/Desktop/hello.ps1 : File C:\users\m.m\Desktop\hello.ps1 cannot 
be loaded because running scripts is 
disabled on this system. For more information, see about_Execution_Policies 
at 
https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ C:/users/m.m/Desktop/hello.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess

The main goal is this:using python to write scripts for powershell.

moh80s
  • 763
  • 1
  • 7
  • 21
  • Seems like a permission error, try running the python script as administrator. – Wasi Oct 11 '19 at 10:46
  • You've shown us `C:\users\m.m\Desktop\hello.ps1` is being targetted, however, you've not shown us the code being ran on this, could you add this to your question. – Matthew Oct 11 '19 at 10:53
  • Dear @Matthew, it's just a simple `print('hello world')` – moh80s Oct 11 '19 at 10:56
  • That would be the Python Syntax, PowerShell it would be `write-host "hello, world!"` – Matthew Oct 11 '19 at 10:58

2 Answers2

1

Make sure you can run powershell scripts (it is disabled by default). Run this as an Administrator into your PowerShell window

Set-ExecutionPolicy RemoteSigned

because the error that you're getting is

cannot be loaded because running scripts is disabled on this system.

Sawant Sharma
  • 738
  • 3
  • 10
1

You're getting that error likely for two reasons, the first is because you're not running PowerShell as an administrator, you should save your script and reload ISE as an administrator.

Secondly, you must set run the following:

Set-ExecutionPolicy RemoteSigned

or

Set-ExecutionPolicy unrestricted

Run this before you run your script.

Additional information on Set-ExecutionPolicy can be found here

Matthew
  • 1,412
  • 2
  • 20
  • 35