Powershell导出带列的csv

时间:2016-11-29 02:09:20

标签: powershell

我想导出csv文件,其中包含列" ParentGroupName"," MemberName"," DisplayName"

目前它正在将三个数据导出到一列中。

class D(object):
  def __getattribute__(s,*a,**ka):
    print "__getattribute__"
    return object.__getattribute__(s,*a,**ka)

  def __getattr__(s,name):
    print "__getattr__"
    return name

  def __get__(s,instance,owner):
    print "__get__"
    return s

1 个答案:

答案 0 :(得分:1)

通过手动构建CSV文件,您自己会头疼。通过为您需要记录的属性找到的每个项目构建自定义对象,然后将其填充到数组中并将该数组导出到CSV文件,可以大大简化这一过程。

function getGroups{
    $Groups += Get-ADGroup -Filter * -SearchBase "ou=Groups,ou=DCM,ou=NTG,dc=prod,dc=main,dc=ntgov" | Select-Object -ExpandProperty samaccountname
    return $Groups
}
$Groups = getGroups
write-host "Groups:" $Groups.Count 

$date = $(get-date).ToString("dd MMM yyyy")
$global:FileName = "Active Directory Group Membership - DCM -" + $date

$results = @();

foreach ($GroupName in $Groups){
        Get-ADGroupMember -Identity $GroupName | Sort-Object $_.SamAccountName | ForEach-Object {
            $ItemProperties = @{
                "ParentGroupName" = (Get-ADGroup -Identity $GroupName).SamAccountName;
                "MemberName" = $_.SamAccountName
            }

            if ($_.ObjectClass -eq 'group') {
                $ItemProperties.Add("DisplayName","-");
            } elseif ($_.ObjectClass -eq 'user') {
                $ItemProperties.Add("DisplayName",(Get-ADUser -Identity $MemberName -Properties DisplayName).DisplayName);
            }
            $MyItem = New-Object -TypeName psobject -property $ItemProperties;
            $Results += $MyItem;
            $ItemProperties = $null;
        }
    } 
$results | export-csv -path "C:\Users\augut\Desktop\$FileName.csv" -NoTypeInformation