title: What is the C# alternative for the below powershell code?
body: <p>I am trying to get a list of services from a remote machine using C# but it doesn't work but the same works when I run the PowerShell script under the same user.</p>
  
  <pre><code> $global:websess = New-PSSession -Computername $webserverNameList.Text -Credential $global:cred -ConfigurationName *JEAconfigname* -Authentication Negotiate
  </code></pre>
  
  <p>The above code is from the PowerShell script that uses the same domain\username to get a list of services from a remote machine. I tried doing the same from my C# code using ServiceController class and also a combination of ConnectionOption class and ManagementScope but I get access denied error.</p>
  
  <pre><code>        ConnectionOptions connection = new ConnectionOptions();
          connection.Username = "domain\username";
          connection.Password = "password";
          connection.Authority = "";
          connection.EnablePrivileges = true;
          connection.Authentication = AuthenticationLevel.PacketPrivacy;
          connection.Impersonation = ImpersonationLevel.Impersonate;
          ManagementScope scope = new ManagementScope(@"\\" + lstServerNames.SelectedValue.ToString() + @"\root\cimv2");
          scope.Connect(); // Fails here: System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'
          ObjectQuery query = new ObjectQuery(
                  "SELECT * FROM Win32_Service WHERE Name like '%Vend%'");
  
          ManagementObjectSearcher searcher =
                new ManagementObjectSearcher(scope, query);
  
          foreach (ManagementObject queryObj in searcher.Get())
          {
              cmbServices.Add(queryObj["Name"].ToString());
          }
  </code></pre>
  
  <p>i have tried this too:</p>
  
  <pre><code>List&lt;ServiceController&gt; serviceList = ServiceController.GetServices(lstServerNames.SelectedValue.ToString()).Where(x =&gt; x.ServiceName.ToLower().StartsWith("vend") || x.ServiceName.ToLower().StartsWith("vstsagent")).ToList(); 
  // Fails here: System.InvalidOperationException: 'Cannot open Service Control Manager on computer '*server name*'. This operation might require other privileges.'
          foreach (ServiceController service in serviceList)
          {
              cmbServices.Add(service.ServiceName);
          }
  </code></pre>
  
  <p>I know the user is now given admin access. The existing PowerShell using Just Enough Administration (JEA) access to run the script.
  <a href="https://msdn.microsoft.com/en-us/library/dn896648.aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/dn896648.aspx</a> </p>