1

I have a power shell script which is executing in PowerShell, but the same code not executing from C#. Here is my code.

PowerShellScript psScript = new PowerShellScript();
            //psScript.AddLine("Import-Module msonline");
            psScript.AddLine("Set-ExecutionPolicy RemoteSigned -Scope CurrentUser");
            psScript.AddLine("$ServiceUser = \"" + this.ServiceUser + "\"");
            psScript.AddLine("$ServicePassword = ConvertTo-SecureString -AsPlainText \"" + this.ServicePassword + "\" -Force");
            psScript.AddLine("$Livecred = New-Object System.Management.Automation.PSCredential -ArgumentList $ServiceUser, $ServicePassword");
            psScript.AddLine("Connect-MsolService -Credential $Livecred");
            psScript.AddLine("$upn = \"" + username + "\"");
            psScript.AddLine("$auth = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement");
            psScript.AddLine("$auth.RelyingParty = '*'");
            psScript.AddLine("$auth.State = 'Enforced'");
            psScript.AddLine("$auth.RememberDevicesNotIssuedBefore = (Get-Date)");
           // psScript.AddLine("Set-MsolUser -UserPrincipalName $upn -StrongAuthenticationRequirements $auth");
            psScript.AddLine("$mfaoff = @()");
            psScript.AddLine("Set-MsolUser -UserPrincipalName $upn -StrongAuthenticationRequirements $mfaoff");


            Console.WriteLine("SCRIPT:");
            Console.WriteLine(psScript.GetScript());

            pshell.AddScript(psScript.GetScript());
            pshell.AddCommand("Out-String");

            PowerShellResponse response = new PowerShellResponse();
            response.InvokeResponse(pshell);
            msox.ResponseList.AddRange(response.PropertyList);
            msox.Success = (response.ErrorList.Count == 0);

I am getting this error.

1.The term 'Connect-MsolService' 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. Cannot find type

2.[Microsoft.Online.Administration.StrongAuthenticationRequirement]: verify that the assembly containing this type is loaded.

Lam Le
  • 1,489
  • 3
  • 14
  • 31
sandeep
  • 449
  • 2
  • 7
  • 22
  • It seems you don't install `MSOnline` module, see this [link](https://learn.microsoft.com/en-us/powershell/azure/active-directory/install-msonlinev1?view=azureadps-1.0). – Shui shengbao Feb 02 '18 at 02:04
  • i found answer to my question in this link.[Check this link](https://stackoverflow.com/questions/43252813/connect-msolservice-is-not-recognized-as-the-name-of-a-cmdlet) – sandeep Feb 02 '18 at 02:43

0 Answers0