pythonpython-3.xpowershell

How to fill PowerShell input with a Python Script?


I've installed PowerShell on a Linux device and I need to access the module ExchangeOnlineManagement. I would like to use a python script to manage any actions automatically on the Powershell Exchange. However, I'm able to connect on PowerShell Exchange but I didn't find a way to fill the input requested by PowerShell Exchange Module.

There is my code:

import subprocess
import sys
def run(cmd):
    completed = subprocess.run(["/xxxx/xxxx/xxxx/xxxx/pwsh", "-Command", cmd], stdout=True, stderr=True)

    return completed

if __name__ == '__main__':
    connect_command = "Connect-ExchangeOnline -CertificateFilePath '/XXX/XXX/XXX/certificate.pfx' -CertificatePassword (Get-Credential).password -AppID 'XXXXXXXXXXXXXXXXXXXXXX' -Organization 'myorg.onmicrosoft.com'"
    connect_info = run(connect_command)
    if connect_info.returncode != 0:
        print("An error occured: %s", connect_info.stderr)
    else:
        print("Connected")

At this moment, PowerShell prompt me this:

Prompt username

I've tried to fill it with "sys.stdout.write('myuser')" but my script is waiting for my output and doesn't read the instruction.

Does anyone have any idea how to manage this?


Solution

  • The argument -Confirm:$false helped me for executing the command and ignoring the prompt.

    Like this:

    Disconnect-ExchangeOnline -Confirm:$false