Search code examples
pythonpowershellazure-active-directoryazure-automationazure-runbook

Trouble running PowerShell command with subprocess library in Python script runbook (Azure automation account)


I'm new to Azure automation, and have a python script that runs fine on the local machine. The script runs a PowerShell command to get sign in logs, and does some string parsing on them before writing to a storage account table. I was able to install all dependencies for the script via the "Python Packages" blade in the automation account. Is there a way to add powershell.exe somewhere so that the subprocess library can be used to run the PowerShell command? Alternatively, is there a library you can import to be able to run the PowerShell command or grab sign in logs from Azure AD without directly using the powershell.exe file?

Also, Microsoft.Powershell.Core is added in the Modules within the automation account. Am I just using the wrong filename and should use something other than powershell.exe? Is there a different module you have to install, or am I referencing it wrong?

Here is the relevant portion of the script:

import subprocess
import sys
import json
import azure.core
from azure.core.credentials import AzureNamedKeyCredential 
from azure.data.tables import TableServiceClient, TableClient 

data = subprocess.check_output(["powershell.exe", "Connect-AzureAD -AccountId [email protected] \n Get-AzureADAuditSignInLogs"]).decode(sys.stdout.encoding)

This throws a "FileNotFound" error for powershell.exe. In the context of an Azure Automation runbook, how can you run powershell commands with the subprocess library, then? Any ideas are much appreciated. Many thanks


Solution

  • I have tested in my environment

    I get the same error as yours if I use subprocess in my python script to run PowerShell command

    This is because the subprocess module is not able to find the powershell.exe path

    For the workaround, you can use either of the options:

    1. You can use PowerShell script instead of python script
    2. You can use MS Graph API in your python code instead of PowerShell commands