Home > front end >  Connect and run PowerShell command from Web API
Connect and run PowerShell command from Web API

Time:09-21

I am trying to run a PowerShell command from a Web Api. All I ever get is this error The term 'Get-MailUser' is not recognized as a name of a cmdlet, function, script file, or executable program. I can run the same code from a PowerShell 7 command and it works fine. I am using the Microsoft PowerShell SDK in the project which is showing at level 7.1. Any help would be greatly appreciated!

This is the code I am using.

          if (powershell == null)
            {
                using (Runspace runspace = RunspaceFactory.CreateRunspace())
                {
                    runspace.Open();
                    powershell = PowerShell.Create();
                    powershell.Runspace = runspace;

                    PSCommand command = new PSCommand();
                    command.AddCommand("Set-ExecutionPolicy").AddArgument("RemoteSigned");
                    command.AddCommand("New-PSSession");
                    command.AddCommand("Import-Module").AddParameter("Name", "PowerShellGet");
                    command.AddCommand("Install-Module").AddParameter("Name", "ExchangeOnlineManagement").AddParameter("Force");
                    command.AddCommand("Import-Module").AddParameter("Name", "ExchangeOnlineManagement");
                    command.AddCommand("Connect-ExchangeOnline").AddParameter("CertificateThumbPrint", "mythumbprint")
                                                                   .AddParameter("AppId", "my app id")
                                                                   .AddParameter("Organization", "mycompany.onmicrosoft.com");
                    command.AddCommand("Get-MailUser").AddParameter("Identity", "myemailaddress");

                    powershell.Commands = command;
                    // Collection<PSObject> results = powershell.Invoke();
                    var t1 = powershell.Invoke<PSSession>();
                }
            }
        }

CodePudding user response:

When you make successive calls to AddCommand, you're effectively composing a pipeline - so the equivalent to your code in PowerShell would be:

Set-ExecutionPolicy RemoteSigned |New-PSSession |Import-Module -Name PowerShellGet |Install-Module -Name ExchangeOnlineManagement -Force |Import-Module -Name ExchangeOnlineManagement |Connect-ExchangeOnline -CertificateThumbPrint mythumbprint -AppId "my app id" -Organization mycompany.onmicrosoft.com |Get-MailUser -Identity myemailaddress

... which is probably not what you intended.

Remember to call AddStatement() in between commands instead:

command.AddCommand("Install-Module").AddParameter("Name", "ExchangeOnlineManagement").AddParameter("Force");
command.AddStatement();
command.AddCommand("Import-Module").AddParameter("Name", "ExchangeOnlineManagement");
command.AddStatement();
// ... and so forth
  • Related