Calling Azure Powershell commands from C#

Prashu 56 Reputation points

I am unable to successfully execute following piece of code. Whenever I try to call Azure commands through C#, it threw an exception ""The term 'Connect-AzureADUser' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.". Is there a way to execute Azure powershell commands through C# ?

In addition to it, I should be able to see the output in the results variable.

PSDataCollection<PSObject> myOutPut = new PSDataCollection<PSObject>();

            InitialSessionState initialState = InitialSessionState.CreateDefault();
            initialState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
            initialState.AuthorizationManager = new System.Management.Automation.AuthorizationManager("O365");
            initialState.LanguageMode = System.Management.Automation.PSLanguageMode.FullLanguage;
            initialState.ImportPSModule(new string[] { "AzureADPreview" });
            Runspace runspace = RunspaceFactory.CreateRunspace(initialState);

            Pipeline pipeline = runspace.CreatePipeline();


            var result = pipeline.Invoke();
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
20,497 questions
{count} votes

Accepted answer
  1. Marilee Turscak-MSFT 36,161 Reputation points Microsoft Employee

    This isn't really Azure Active Directory related (as it is tagged), but my suspicion is that you are missing the right assembly reference since you appear to be calling the AddScript() and AddCommand() methods correctly. You will need the latest Nuget package not the old System.Management.Automation one that might be referenced in a some of the documentation.

2 additional answers

Sort by: Most helpful
  1. Prashu 56 Reputation points

    It may be helpful for others. I added $now = [System.DateTime]::Now New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "Test123" -Type AsymmetricX509Cert -Usage Verify -Value $keyValue -StartDate $now -EndDate $cert.GetExpirationDateString()

    This has fixed Key credential end date is invalid error.

    1 person found this answer helpful.

  2. Daniel Bielski 1 Reputation point

    Hello, PrashuDA. How are you?

    I am making an application to study with this same resource of invoking azure and msol in powershell through C #. Could you share your application / source code so I can see it? It will help me a lot. Hugs and see you soon!