将 ICollection 转换为 psobject 以传递给 ft 或 export-csv



我使用powershell通过调用DirectoryServices.DirectorySearcher来执行一些ADSI/LDAP查询,因为我需要提供一组备用凭据。一旦我执行了一个FindAll()方法,我就会得到一个实现ICollection DirectoryServices.SearchResultCollection。从那里开始,如果我想将该输出通过管道传输到ft或export-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 帮助程序库,但它们对我没有帮助,因为我需要使用替代信条,而且它们中的大多数都是以这种方式中断的。

试试这个,它将搜索对象上找到的任何属性复制到一个新的 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
}

最新更新