.net 将ICollection转换为psobject以传递到ft或导出csv
我使用powershell通过调用DirectoryServices.DirectorySearcher来执行一些ADSI/LDAP查询,因为我需要提供一组可选的凭据。执行.net 将ICollection转换为psobject以传递到ft或导出csv,.net,powershell,.net,Powershell,我使用powershell通过调用DirectoryServices.DirectorySearcher来执行一些ADSI/LDAP查询,因为我需要提供一组可选的凭据。执行FindAll()方法后,我会得到一个DirectoryServices.SearchResultCollection,它实现了ICollection。从那以后,如果我想通过管道将输出传输到ft或导出csv,我必须创建一个新的psobject,将我感兴趣的属性复制到一个新的psobject,如下所示: $dEntry = Ne
FindAll()
方法后,我会得到一个DirectoryServices.SearchResultCollection
,它实现了ICollection
。从那以后,如果我想通过管道将输出传输到ft或导出csv,我必须创建一个新的psobject,将我感兴趣的属性复制到一个新的psobject,如下所示:
$dEntry = New-Object DirectoryServices.DirectoryEntry("LDAP://acme.com/cn=sites,cn=configuration,dc=acme,dc=com","user","pass");
$searcher=New-Object DirectoryServices.DirectorySearcher($dEntry);
$searcher.Filter="(objectClass=siteLink)";
$searcher.PropertiesToLoad.Add("siteList");
$searcher.PropertiesToLoad.Add("cost");
$searcher.PropertiesToLoad.Add("replInterval");
$searcher.PropertiesToLoad.Add("cn");
$searcher.FindAll() |%{
$count=$_.Properties.sitelist.Count;
$p=@{"cn"=[string]$_.Properties.cn; "sites"=$count;
"cost"=[string]$_.Properties.cost;
"replInterval"=[string]$_.Properties.replInterval;
};
if ($count>=2) {
$p["mesh"]=$count;
}else{
$p["mesh"]=$count*$count;
}
New-Object psobject -Property $p
}
这看起来相当乏味,而且这可能是一项非常常见的任务,因此肯定有一种更简单的方法来完成。是的,我知道AD-helper库,但它们对我没有帮助,因为我需要使用备用凭据,而且大多数凭据都是这样断开的。试试这个,它会将搜索对象上找到的任何属性复制到新的psobject:
$searcher.FindAll() | ForEach-Object {
$pso = New-Object PSObject
$_.PSBase.Properties.GetEnumerator() | Foreach-Object{
Add-Member -InputObject $pso -MemberType NoteProperty -Name $_.Name -Value ($_.Value | foreach {$_})
}
$pso
}
我建议将($count>=2)
改为($count-ge 2)
。答案不简单,但最好(也是唯一的)