以下 powershell 代码的 C# 替代方案是什么?

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

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

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

以上代码来自 PowerShell 脚本,该脚本使用相同的 domain\username 从远程计算机获取服务列表。我尝试使用 ServiceController class 以及 ConnectionOption class 和 ManagementScope 的组合从我的 C# 代码中执行相同的操作,但出现拒绝访问错误。

        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

你用错了ManagementScope constructor。您没有指定选项。

尝试:

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

也通读上面链接文档中的示例。