AdUsers2Csv.ps1


<#PSScriptInfo
 
.VERSION 1.1
 
.GUID 9977b7fa-d67e-44ac-a04d-3708aa541b51
 
.AUTHOR Kalichuza
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
#>


<#
 
.DESCRIPTION
 Take a csv snapshot of the users in an ad search-base
 
#>
 
[CmdletBinding()]
param (
    [Parameter(Mandatory=$true)]
    [string]$ADServer,

    [Parameter(Mandatory=$true)]
    [string]$SearchBase,

    [Parameter(Mandatory=$false)]
    [string]$OutputPath = ".\"
)

# Ensure the output directory exists
if (!(Test-Path -Path $OutputPath)) {
    New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null
}

# Generate the CSV file path dynamically
$LogDate = Get-Date -Format "yyyyMMddhhmm"
$csvfile = Join-Path -Path $OutputPath -ChildPath "ALLADUsers_$LogDate.csv"

# Import Active Directory module
Import-Module ActiveDirectory

# Get Admin credentials
$GetAdminact = Get-Credential -Message "Enter admin credentials for $ADServer"

# Retrieve AD users excluding those marked as 'Migrated'
$AllADUsers = Get-ADUser -Server $ADServer `
    -Credential $GetAdminact `
    -SearchBase $SearchBase `
    -Filter * -Properties * |
    Where-Object { $_.info -ne 'Migrated' }

# Select user properties and export to CSV
$AllADUsers |
Select-Object @{Label = "FirstName"; Expression = {$_.GivenName}},
              @{Label = "LastName"; Expression = {$_.Surname}},
              @{Label = "DisplayName"; Expression = {$_.DisplayName}},
              @{Label = "LogonName"; Expression = {$_.sAMAccountName}},
              @{Label = "Fulladdress"; Expression = {$_.StreetAddress}},
              @{Label = "City"; Expression = {$_.City}},
              @{Label = "State"; Expression = {$_.st}},
              @{Label = "PostCode"; Expression = {$_.PostalCode}},
              @{Label = "Country/Region"; Expression = {if ($_.Country -eq 'GB') {'United Kingdom'} Else {''}}},
              @{Label = "JobTitle"; Expression = {$_.Title}},
              @{Label = "Company"; Expression = {$_.Company}},
              @{Label = "Department"; Expression = {$_.Department}},
              @{Label = "Office"; Expression = {$_.OfficeName}},
              @{Label = "Phone"; Expression = {$_.telephoneNumber}},
              @{Label = "Email"; Expression = {$_.Mail}},
              @{Label = "Manager"; Expression = {(Get-ADUser $_.Manager -Server $ADServer -Properties DisplayName).DisplayName}},
              @{Label = "AccountStatus"; Expression = {if ($_.Enabled -eq $true) {'Enabled'} Else {'Disabled'}}},
              @{Label = "LastLogOnDate"; Expression = {$_.lastlogondate}} | 
Export-Csv -Path $csvfile -NoTypeInformation

Write-Host "Export completed successfully. File saved to: $csvfile"