Issues in executing powershell script from web service RRS feed

  • Question

  • Hi Guys,

    1) Below is my powershell script:

    #Accept input parameters  
        [Parameter(Position=0, Mandatory=$false, ValueFromPipeline=$true)]  
        [string] $Office365Username,  
        [Parameter(Position=1, Mandatory=$false, ValueFromPipeline=$true)]  
        [string] $Office365Password,

    #Remove all existing Powershell sessions  
    Get-PSSession | Remove-PSSession   

    #Did they provide creds?  If not, ask them for it.
    if (([string]::IsNullOrEmpty($Office365Username) -eq $false) -and ([string]::IsNullOrEmpty($Office365Password) -eq $false))

        $SecureOffice365Password = ConvertTo-SecureString -AsPlainText $Office365Password -Force      
        #Build credentials object  
        $Office365Credentials  = New-Object System.Management.Automation.PSCredential $Office365Username, $SecureOffice365Password  
        #Build credentials object  
        $Office365Credentials  = Get-Credential

    #Create remote Powershell session  
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Office365Credentials -Authentication Basic -AllowRedirection
    #Import the session  
    Import-PSSession $Session
    $result=Get-DistributionGroup -ResultSize Unlimited  
    return  $result
    #Clean up session  
    Remove-PSSession $Session

    2) Below is my C# code

    public string GetAllGroups()
                int count = 1;
                string getDListScript = @"C:\inetpub\wwwroot\O365Service\Scripts\GetDList.ps1";
                string userName = "j*****";
                string password = "****";
                    using (var ps = PowerShell.Create())
                        Runspace runSpace = RunspaceFactory.CreateRunspace();
                        ps.Runspace = runSpace;

                        ps.AddCommand(getDListScript).AddParameter("Office365Username", userName).AddParameter("Office365Password", password);
                        //IAsyncResult async = ps.BeginInvoke();
                        //StringBuilder stringBuilder = new StringBuilder();
                     var   results = ps.Invoke();
                     PSDataCollection<ErrorRecord> errors = ps.Streams.Error;
                     if (errors != null && errors.Count > 0)
                         StringBuilder sb = new StringBuilder();
                         foreach (ErrorRecord err in errors)
                         System.IO.File.WriteAllText(@"C:\inetpub\wwwroot\RestService\bin\err.text", sb.ToString());

                     count = results.Count;

                catch (Exception ex)
                    return ex.Message.ToString();
                return count.ToString();


    When i am executing the C# code on server from Console application it is working fine but when i am executing it from Webservice it is giving me the below exception

    [outlook.office365.com] Connecting to remote server outlook.office365.com failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.Cannot validate argument on parameter 'Session'. The argument is null. Provide a valid value for the argument, and then try running the command again.The term 'Get-DistributionGroup' 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.

    I have set execution policy to unrestricted of the server.

    Please Help me on this.



    Friday, June 5, 2015 1:39 PM

All replies

  • I would suggest you just invoke the cmdlet directly from your managed code eg https://msdn.microsoft.com/en-us/library/office/ff326159%28v=exchg.150%29.aspx instead of trying to do it the way you are which is complicated. eg

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Collections.ObjectModel;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    namespace TestpsCons
        class Program
            static void Main(string[] args)
                String AdminUserName = "User@domain.com";
                String Password = "password";
                System.Security.SecureString secureString = new System.Security.SecureString();
                foreach (char c in Password)
                PSCredential credential = new PSCredential(AdminUserName, secureString);
                WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri("https://outlook.office365.com/PowerShell"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
                connectionInfo.SkipCACheck = true;
                connectionInfo.SkipCNCheck = true;
                connectionInfo.NoEncryption = false;
                connectionInfo.MaximumConnectionRedirectionCount = 4;
                Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(connectionInfo);
                Command getDLList = new Command("Get-DistributionGroup");
                getDLList.Parameters.Add("ResultSize", "Unlimited");
                Pipeline plPileLine = runspace.CreatePipeline();
                Collection<PSObject> RsResultsresults = plPileLine.Invoke();
                foreach (PSObject psObj in RsResultsresults) {

    Monday, June 8, 2015 4:37 AM
  • Hi Glen,

    I am getting authentication error but I am not able to figure it out.

    Here is error details.

    Error:System.Management.Automation.Remoting.PSRemotingTransportException: Connecting to remote server outlook.office365.com failed with the following error message : [ClientAccessServer=SG2PR03CA0041,BackEndServer=,RequestId=e4e42712-90ad-4c61-8d7e-0f07abc15c79,TimeStamp=6/8/2015 5:38:58 AM] Access Denied For more information, see the about_Remote_Troubleshooting Help topic.
       at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
       at System.Management.Automation.Runspaces.Internal.RunspacePoolInternal.EndOpen(IAsyncResult asyncResult)
       at System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal.Open()
       at System.Management.Automation.RemoteRunspace.Open()
       at DistributionList.Service.DistributionList.GetAllGroups().

    I have few queries.

    1) I am getting error only when i am accessing it from WCF web service. In console application it is running fine.

    2) Which URl I should use in  WsManConnectionInfo. Is it Domain url or same as above?


    • Edited by Samira123 Monday, June 8, 2015 7:20 AM
    Monday, June 8, 2015 5:49 AM
  • 1. I would say you have a username and password issue with your WCF apps eg try using the wrong username and password in you console apps and you'll get the same error.

    2. It should be https://outlook.office365.com/PowerShell


    Tuesday, June 9, 2015 4:50 AM
  • You are right Glen. When I am passing wrong credentials then it is throwing error but with specification.

    Error:System.Management.Automation.Remoting.PSRemotingTransportException: Connecting to remote server outlook.office365.com failed with the following error message : [ClientAccessServer=BLUPR06CA0011,BackEndServer=,RequestId=c29c7583-9d6e-42f5-9d0f-331c26224def,TimeStamp=6/9/2015 6:14:10 AM] [FailureCategory=LiveID-InvalidCreds].

    Access Denied For more information, see the about_Remote_Troubleshooting Help topic.

    But when assigning valid credential I am getting same error at line Runspace.open(). Moreover My user is a global admin in Office365. Am I missing any  configuration in Office365 or PowerShell?

    Tuesday, June 9, 2015 9:44 AM
  • You could try some tracing http://windowsitpro.com/blog/tools-troubleshooting-powershell-remoting-and-winrm-part-2 to get more information


    Wednesday, June 10, 2015 6:49 AM
  • Thanks a lot Glen. It was actually  IIS pool which was denying access for security reasons. Because IIS does'nt

    allow anonymous user to run powershell scripts.

    Friday, June 12, 2015 5:29 AM