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

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 (" + "\"[email protected]\"" + ", $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.

6

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!

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like