powershellactive-directory

Need to export the output of powershell script of to csv file


I have script to get the count of a Security group from active directory. But i need to export those output to csv file. In csv file i need input data in one column and output will be in next column.

Here the script

$Groups = Get-Content D:\group1.txt
foreach ($Group in $Groups) {
$ADInfo = Get-ADGroup -Identity $Group -Properties Members
$AdInfo.Members.Count 
}

Current output

current output.


Solution

  • You can use the Export-Csv cmdlet to export data to a CSV file. It'll create 1 row per object you pipe to it, so all you need to do is construct objects with the group name and the count as property values:

    # read group names from file
    $groupNames = Get-Content D:\group1.txt 
    
    # fetch the group members
    $groupsWithMembers = $groupNames |Get-ADGroup -Properties Members 
    
    # create 1 new object per group, containing 2 properties - Name and Count
    $groupMemberCounts = $groupsWithMembers |Select-Object Name,@{Name='Count';Expression={$_.Members.Count}}
    
    # export to CSV
    $groupMemberCounts |Export-Csv path\to\export.csv -NoTypeInformation
    

    You could also compose a single pipeline that does all 4 steps:

    Get-Content D:\group1.txt |Get-ADGroup -Properties Members |Select-Object Name,@{Name='Count';Expression={$_.Members.Count}} |Export-Csv path\to\export.csv -NoTypeInformation