以下PowerShell代码的C#替代方法是什么?

时间:2017-10-13 12:02:12

标签: c# .net powershell wmi wmi-query

我正在尝试使用C#从远程计算机获取服务列表,但它不起作用,但当我在同一用户下运行PowerShell脚本时,同样有效。

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

以上代码来自PowerShell脚本,该脚本使用相同的域\用户名来从远程计算机获取服务列表。我尝试使用ServiceController类从我的C#代码中做同样的事情,也尝试使用ConnectionOption类和ManagementScope,但是我得到访问被拒绝错误。

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

我也试过这个:

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

我知道用户现在已获得管理员权限。现有的PowerShell使用Just Enough Administration(JEA)访问来运行脚本。 https://msdn.microsoft.com/en-us/library/dn896648.aspx

1 个答案:

答案 0 :(得分:0)

您使用了错误的ManagementScope constructor。您没有指定选项。

尝试:

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

请仔细阅读上面链接文档中的示例。