public/Export-Users.ps1

Function Export-Users {

    <#
    .SYNOPSIS
        This function allows you to easily export all users or certain group members from AD to a CSV file
      
      
    .NOTES
        Name: Export-Users
        Author: Elliott Marter
      
      
    .EXAMPLE
        Export-Users -group "office"
      
      
    .LINK
        https://www.powershellgallery.com/profiles/elliottmarter
    #>


    [cmdletbinding(SupportsShouldProcess=$True)]
    [CmdletBinding(DefaultParameterSetName='all')]

    Param(

        [Parameter(ParameterSetName='all', Position=0)]
        [Switch]$all,

        [Parameter(ParameterSetName='group', Position=0)]
        [String]$group


    )


    # Get Current Date
    $Date = Get-Date -UFormat %d-%m-%y

    if ($all) {

        # Get ALL users in domain that are NOT disabled
        $Users = Get-ADUser -filter {enabled -eq $true} -Properties Description

        # Export to a CSV file on desktop
        $Users |
        Sort-Object Description,Name |
        Select-Object Name, @{Label="Username";Expression="SamAccountName"}, @{Label="Role / Intake";Expression="Description"} |
        ConvertTo-Csv -NoTypeInformation |
        Out-File -FilePath "$Home\Desktop\Full User Export $Date.csv"

        }



    if ($group) {

        if ($group -like "*student*") {

            $Users = Get-ADGroupMember -Identity $group -Recursive

            $Users |
            ForEach-Object {Get-ADUser -Identity $_.SamAccountName -Properties Description} |
            Sort-Object Description,Name |
            Select-Object Name,@{Label="Username";Expression="SamAccountName"}, @{Label="Intake Year";Expression="Description"} |
            ConvertTo-Csv -NoTypeInformation |
            Out-File -FilePath "$Home\Desktop\$group Users Export $Date.csv"
        
           } else {

            $Users = Get-ADGroupMember -Identity $group -Recursive

            $Users |
            ForEach-Object {Get-ADUser -Identity $_.SamAccountName -Properties Description} |
            Sort-Object Description,Name |
            Select-Object Name,@{Label="Username";Expression="SamAccountName"}, @{Label="Role";Expression="Description"} |
            ConvertTo-Csv -NoTypeInformation |
            Out-File -FilePath "$Home\Desktop\$group Users Export $Date.csv"
        
        }

    }
    
}