什么是下面的PowerShell代码的C#替代品?
问题描述:
我想从使用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
答
您使用的是错误的ManagementScope constructor。你没有指定选项。
尝试:
ManagementScope scope = new ManagementScope(@"\\" + lstServerNames.SelectedValue.ToString() + @"\root\cimv2", connection);
scope.Connect();
通过阅读上面的链接的文档中的例子了。
+0
我很抱歉,我没有更新代码。我已经添加了连接选项,但它仍然无法工作。事情是登录用户有权访问远程服务器,但我不能让它加载服务等。使用PowerShell,它使用JEA的想法(刚好足够的管理)。我想知道我们是否有类似于C#的东西,所以我可以用同样的方式调用它 –
[在C#中连接到Microsoft Exchange PowerShell]的可能重复(https://*.com/questions/36236897/connect-to-microsoft-exchange-powershell-within-c-sharp)。这个问题的答案应该让你接近你想要做的事情。 –
如何显示失败的C#应用程序的一些示例代码?没有太大的意义,分享工作PoSh示例,并寻求与PowerShell的帮助... – Clijsters
@Clijsters我已更新代码 –