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 Server Management
Exchange Server Management
Exchange Server: A family of Microsoft client/server messaging and collaboration software.Management: The act or process of organizing, handling, directing or controlling something.
7,498 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,455 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,831 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 45,831 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.