Reputation: 271
Is there a way to run powershell code in python? I've been searching around and all I'm finding is how to run a separate PS script file in python, but nothing about running PS code.
Example: Let's say I want to run this command from inside a Python script\program...
Start-Process -filepath "Path\Filename.exe" -wait
I understand in that example I could just run the file using Python. I'm looking into writing a Python app, but it would use some powershell code behind the scenes to actually do what it needs to do. In the case for my app idea, it would connect to Office 365 and manipulate users\account info (add, remove, etc) and things you can't do on the 365 admin site. I already have a PS script to do most of this, but I'm looking into a GUI interface and python seems to be the better choice for GUI (so far as what I've seen and played with).
If this isn't possible, or if it's more pain than it's worth I'd appreciate some suggestions. Should I look into C# or something like that? Python seemed easier to understand.
Thanks.
Upvotes: 4
Views: 1767
Reputation: 4517
Just start powershell.exe (untested)
os.system("powershell.exe", "script.ps1")
You may need an additional parameters to specify path and execution policy.
Upvotes: 1
Reputation: 94
If you Want to embed PowerShell script in exe, vc++ is probably the way to go.
You can use system
function in <stdlib>
to run commands in cmd
here is the code:
#include "stdafx.h"
#include <stdlib.h>
using namespace std;
int main()
{
system("@powershell -NoProfile -ExecutionPolicy Bypass <your PSScript path>");
return 0;
}
but this code will require you have the ps1
file on your local box.
my suggestion is to run if from the remote. host you ps1
file on GitHub or gist
#include "stdafx.h"
#include <stdlib.h>
using namespace std;
int main()
{
system("@powershell -NoProfile -ExecutionPolicy Bypass -command (new-object net.webclient).downloadstring('<url to your script>")');
return 0;
}
Upvotes: 2
Reputation: 1164
Couldn't you just write a powershell script file and then call it? (untested)
f = open("script.ps1")
f.write(...) #Script you want to run
f.close()
os.system("powershell.exe", "script.ps1")
Upvotes: 0