我想從使用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
[在C#中連接到Microsoft Exchange PowerShell]的可能重複(https://stackoverflow.com/questions/36236897/connect-to-microsoft-exchange-powershell-within-c-sharp)。這個問題的答案應該讓你接近你想要做的事情。 –
如何顯示失敗的C#應用程序的一些示例代碼?沒有太大的意義,分享工作PoSh示例,並尋求與PowerShell的幫助... – Clijsters
@Clijsters我已更新代碼 –