Home:ALL Converter>PowerShell script fails when called from Python, but can when run via PowerShell

PowerShell script fails when called from Python, but can when run via PowerShell

Ask Time:2016-10-26T20:11:52         Author:Dylan Knight

Json Formatter

I have an issue, where a simple PowerShell script, when called from Python, fails to find the module MSOnline, but when running the PowerShell script from CMD/PS it runs as expected.

When the PowerShell script is run on it's own, it works perfect, and I feel as the Python script is working fine as it is pulling in the errors formatted from PowerShell as I want the format to be, but as it can't find the module, I am just at a loss.

Python script that calls the Powershell script and pulls the output.

import subprocess, sys

def powershell(cmd):
    out = []
    p = subprocess.Popen(["powershell.exe", cmd], stdout=sys.stdout)
    line = p.communicate()
    out.append(line)
    for line in out:
        print(line)

powershell(r"Path to Powershell script")

PowerShell script that pulls users from Office 365 Online

Import-Module MSOnline
$username = "username"
$password = cat C:\Users\user\Documents\folder\securestring.txt | ConvertTo-SecureString
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
Connect-MsolService -Credential $cred
Get-MsolUser

Can anyone shed some light on the reason that when the PowerShell script is called from Python, that it fails to import the MSOnline module, local computer's execution policy is set to "Unrestricted".

Author:Dylan Knight,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/40261951/powershell-script-fails-when-called-from-python-but-can-when-run-via-powershell
yy