我在 PowerShell 中有以下代码片段,它返回了远程 PC 上的本地管理员所需的信息。我正在尝试将此代码转换为 C#,但一直不太顺利。
$ADMINS = get-wmiobject -computername $computername -Credential $Credential -query "select * from win32_groupuser where GroupComponent=""Win32_Group.Domain='$computername',Name='administrators'""" | % {$_.partcomponent}
我能够在 C# 中获得一个基本的 wmi 查询,如下所示: 方法
public IEnumerable<CimInstance> WmiQuerier(CimSession session , string wmiquery)
{
try
{
string Namespace = @"root\cimv2";
IEnumerable<CimInstance> CimInstances = new List<CimInstance>();
CimInstances = session.QueryInstances(Namespace, "WQL", wmiquery);
//IEnumerable<CimInstance> CimInstances2 = CimInstances.SelectMany()
return CimInstances;
}
catch (Exception ex )
{
Console.WriteLine(ex.Message);
throw;
}
测试
[Test]
public void CimQuery()
{
string querystring = "SELECT * FROM win32_groupuser";
Wmi wmi = new Wmi();
NetworkCredential mynetcred = new NetworkCredential("Domain\\User", "Password%");
CimCredential mycimCred = wmi.ConvertCred(mynetcred);
CimSession mySession = wmi.WmiConnection(testcomp, mycimCred);
IEnumerable<CimInstance> querierResults = wmi.WmiQuerier(mySession, querystring).Take(5).ToList();
Assert.IsInstanceOf<IEnumerable<CimInstance>>(querierResults);
}
}
但是,当我尝试添加任何类型的 Where 子句时,就像我在 powershell 代码中所做的那样,(请参阅下面的尝试)
"SELECT * FROM win32_groupuser Where GroupComponent = \"Win32_Group.Domain='MachineName',Name='administrators' \""
我得到了错误
Microsoft.Management.Infrastructure.CimException: 'The WS-Management service cannot process the request. The WQL query is invalid. '
我在 WQL 字符串中做错了什么?
最佳答案
这是一个有效的查询。我知道一件事......WQL 的语法极其敏感且无情......尤其是关于空格和引号嵌套。有趣的是,大写/小写都没问题:
using System.Management;
//....
var domainName = "YourDomainName";
var groupName = "Administrators";
var wql = string.Format
(
@"select partcomponent from win32_groupuser where groupcomponent='Win32_Group.Domain=""{0}"",Name=""{1}""'",
domainName,
groupName
);
foreach ( var thing in new ManagementObjectSearcher( wql ).Get( ) )
{
foreach ( var property in thing.Properties )
{
//--> And then, if you want the account object...
var path = new ManagementPath( property.Value as string );
var account = new ManagementObject( path );
foreach ( var acctProp in account.Properties )
{
Console.WriteLine( $"{acctProp.Name}={acctProp.Value}" );
}
}
}
编辑:真讨厌,我添加了代码来获取引用的 Win32_Account 对象...因为 partcomponent
的值是对该帐户对象的限定引用。
关于这个 powershell 片段的 C# 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54030966/