2017-10-13 122 views
-2

我想從使用C#的遠程計算機獲取服務列表,但它不起作用,但在同一用戶下運行PowerShell腳本時工作正常。什麼是下面的PowerShell代碼的C#替代品?

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

上面的代碼是從使用相同的域\用戶名從遠程計算機獲取服務的列表中的PowerShell腳本。我嘗試從我的C#代碼使用ServiceController類和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

+0

[在C#中連接到Microsoft Exchange PowerShell]的可能重複(https://stackoverflow.com/questions/36236897/connect-to-microsoft-exchange-powershell-within-c-sharp)。這個問題的答案應該讓你接近你想要做的事情。 –

+0

如何顯示失敗的C#應用​​程序的一些示例代碼?沒有太大的意義,分享工作PoSh示例,並尋求與PowerShell的幫助... – Clijsters

+0

@Clijsters我已更新代碼 –

回答

0

您使用的是錯誤的ManagementScope constructor。你沒有指定選項。

嘗試:

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

通過閱讀上面的鏈接的文檔中的例子了。

+0

我很抱歉,我沒有更新代碼。我已經添加了連接選項,但它仍然無法工作。事情是登錄用戶有權訪問遠程服務器,但我不能讓它加載服務等。使用PowerShell,它使用JEA的想法(剛好足夠的管理)。我想知道我們是否有類似於C#的東西,所以我可以用同樣的方式調用它 –