Search code examples
pythonpowershellscriptingpycharm

Python: Running Powershell Command inside Python script using Pycharm


I have been trying to figure out a way to run Powershell commands inside a Pycharm project where I can make more complicated scripts using Python. I have been searching for an answer but I have only found a few people even ask this question. I have already verified that my Terminal inside Pycharm is set to PowerShell.

Is there a way to combine a Powershell command inside Python? If so is there a way to do this inside Pycharm?


Solution

  • I was able to research more about the subprocess module and I was able to find a way to do this inside a python project. Below I put a snippet of a very simple command ran with powershell that outputted what I expected so I can add to that.

    import subprocess, sys
    
    computer_name = "L8694C"
    
    p = subprocess.Popen(
        ["powershell.exe", "Get-ADComputer " + computer_name+ " | Select-Object Name"],
        stdout=sys.stdout)
    
    p.communicate()