4
  1. Below is my powershell script:

    #Accept input parameters  
    Param(  
        [Parameter(Position=0, Mandatory=$false, ValueFromPipeline=$true)]  
        [string] $Office365Username,  
        [Parameter(Position=1, Mandatory=$false, ValueFromPipeline=$true)]  
        [string] $Office365Password,
        [string]$GroupName
    )
    
    #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  
    }
    else
    {   
        #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
    #cmds
    
    $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 = "****";
             try
             {
                 using (var ps = PowerShell.Create())
                 {
                     Runspace runSpace = RunspaceFactory.CreateRunspace();
                     runSpace.Open();
                     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)
                      {
                          sb.Append(err.ToString());
                      }
                      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.

tukan
  • 17,050
  • 1
  • 20
  • 48
  • 1
    Configure the webservice user as an admin user. Basically, if it is an IIS web service, setup the application pool with an admin user. – Hozikimaru Jun 05 '15 at 15:08
  • 2
    @SurgeonofDeath - if this is an internet facing machine and site then that's a very bad idea. For things that need elevated rights you should sandbox such functionality in a separate process such as a windows service. – Kev Jun 05 '15 at 15:36
  • @Kev agreed. We need this information in that case – Hozikimaru Jun 05 '15 at 15:45
  • IIS does not allow you to run Windows processing for security reasons. maybe this [link](https://stackoverflow.com/questions/8414514/iis7-does-not-start-my-exe-file-by-process-start) can help you. – xwpedram Feb 08 '21 at 17:04
  • Add transcription and debugging to your PS script: `try {Stop-Transcript} catch {}; $pref = [System.Management.Automation.ActionPreference]::Continue; $VerbosePreference = $pref; $DebugPreference = $pref; $InformationPreference = $pref; $WarningPreference = $pref; Start-Transcript -Path "C:\LOG\pstest_$([DateTimeOffset]::Now.ToUnixTimeSeconds()).log.txt" -EA Stop;`. Use `-AllowClobber` on `Import-Session`. Validate `$null -ne $session`. Validate command using `Try-Catch` around `Get-Command` – filimonic Feb 09 '21 at 21:23
  • you could create a Scheduled task or Powershell scheduled task or job that does a one time run elevated as admin that could carry out this command. – Thom Schumacher Feb 10 '21 at 18:35
  • @xwpedram can you expand what you mean by “IIS does not allow you to run Windows processing” please? – Caltor Feb 10 '21 at 22:03

0 Answers0