Search code examples
c#.netpowershellwmiwmi-query

What is the C# alternative for the below powershell code?


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.

 $global:websess = New-PSSession -Computername $webserverNameList.Text -Credential $global:cred -ConfigurationName *JEAconfigname* -Authentication Negotiate

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.

        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());
        }

i have tried this too:

List<ServiceController> serviceList = ServiceController.GetServices(lstServerNames.SelectedValue.ToString()).Where(x => 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);
        }

I know the user is now given admin access. The existing PowerShell using Just Enough Administration (JEA) access to run the script. https://msdn.microsoft.com/en-us/library/dn896648.aspx


Solution

  • You're using the wrong ManagementScope constructor. You're not specifying the options.

    Try:

    ManagementScope scope = new ManagementScope(@"\\" + lstServerNames.SelectedValue.ToString() + @"\root\cimv2", connection);
    scope.Connect();
    

    Read through the example in the linked document above, too.