The term 'Connect-AzureAD' is not recognized as the name of a cmdlet

Viewed 64081

Running powershell script from C# application in Azure AD.

Added below DLL reference

  • System.Management.Automation
  • Microsoft.Online.Administration.Automation.PSModule.Resources
  • Microsoft.Online.Administration.Automation.PSModule

Runspace runspace = RunspaceFactory.CreateRunspace();
                runspace.Open();
                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript("Import-Module AzureAD -Force;");
                pipeline.Commands.AddScript("$password = ConvertTo-SecureString " + "\"abc1234\"" + " -AsPlainText -Force");
                pipeline.Commands.AddScript("$Cred = New-Object System.Management.Automation.PSCredential (" + "\"abc@abc.com\"" + ", $password)");
                pipeline.Commands.AddScript("Connect-AzureAD -Credential $Cred");
                pipeline.Commands.AddScript("Get-AzureADApplication -Filter " + "\"DisplayName eq " + "\'PortalTestApp\'" + "\"");
                var result = pipeline.Invoke();

Getting Error:

The term 'Connect-AzureAD' 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.

2 Answers

I had an issue with PowerShell v7, unlike PS v5, you have to import the module after installation with Import-Module AzureAD. The error is identical to if you haven't imported it after installing it from a module source like PSGallery.

@user1638526 As mike mentioned, you should install the AzureAD module first.

You can follow the below steps:

Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force

Import-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201

Install-Module AzureAD -Force

-Force suppresses the user input prompts and allows the script to run in the background.

Reference: How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

About for how to call PowerShell command or PS1 file using C# you can also refer to link or another SO Thread.

Hope this helps!

Related