Get the total number and export the list to csv or other format

IT 140 Reputation points
2023-12-04T15:42:32.9366667+00:00

I use the below command to find out how many users/account under specific Department .

I need your kind help to amend or new command to find the total number and how to export the list into CSV file or other format.

Get-Contact -Filter "Department -eq 'Year 8'" | Get-MailContact | Format-List Name,CustomAttribute15

Exchange | Exchange Server | Management
Exchange | Exchange Server | Management
The administration and maintenance of Microsoft Exchange Server to ensure secure, reliable, and efficient email and collaboration services across an organization.
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Answer accepted by question author
  1. Rich Matheisen 48,026 Reputation points
    2023-12-09T00:05:12.2033333+00:00

    This adds a 3rd column named "Total" that will be empty. At the end of the contacts the total number of contacts will be found in the "Total" column and the Name and CustomAttribute15 columns will be empty.

    $c = 0
    Get-Contact -Filter "Department -eq 'Year 8'"|
        ForEach-Object{
            $c++
            Get-MailContact $_.distinguishedname |
                Select-Object Name,CustomAttribute15,Total
    } | Export-CSV c:\junk\somefilename.csv -NoTypeInformation
    [PSCustomObject]@{
        Name = ""
        CustomAttribute15 = ""
        Total = $c
    } | Export-CSV c:\junk\somefilename.csv -NoTypeInformation -Append
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 48,026 Reputation points
    2023-12-04T19:19:56.07+00:00

    Something like this might be what you're trying to fo:

    $c = 0
    Get-Contact -Filter "Department -eq 'Year 8'"|
        ForEach-Object{
            $c++
            Get-MailContact $_.distinguishedname |
                Select-Object Name,CustomAttribute15
    } | Export-CSV c:\junk\somefilename.csv -NoTypeInformation
    Write-Host "There are $c contacts in the department"
    

    EDIT: Changed Get-MailContact $contact.distinguishedname to Get-MailContact $_.distinguishedname

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.