【问题标题】:Convert ICollection to a psobject for passing to ft or export-csv将 ICollection 转换为 psobject 以传递给 ft 或 export-csv
【发布时间】:2012-07-04 08:11:37
【问题描述】:

我使用 powershell 通过调用 DirectoryServices.DirectorySearcher 来执行一些 ADSI/LDAP 查询,因为我需要提供一组替代凭据。一旦我执行了一个FindAll() 方法,我就会得到一个实现ICollectionDirectoryServices.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 助手库,但它们对我没有帮助,因为我需要使用备用凭据,而且其中大多数都以这种方式破坏。

【问题讨论】:

  • 我建议把($count>=2)改成($count -ge 2)

标签: .net powershell


【解决方案1】:

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

【讨论】:

  • 不是简短的,但最好的(也是唯一的)答案
猜你喜欢
  • 1970-01-01
  • 2016-03-13
  • 2011-03-15
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
  • 2015-11-10
  • 1970-01-01
相关资源
最近更新 更多