I'm having issues with optimizing this PowerShell script. It's currently taking 8 hours to complete. I know the issue is the Get-AllAzureADUsers Function due to the ForEach formula. I am wanting to speed this up by only needing it to query the data stored in a variable instead of the system for all 80k users in our tenant but am struggling with this. I'm still new to powershell but need this to pull reports on a weekly basis and really am hoping to try to cut this run time down.
param (
[string]$path = "C:\Temp\ADUsers-$((Get-Date -format "MM-dd-yyyy").ToString()).csv"
Function Get-Users{
process {
$properties = @(
'ObjectId',
'@{N="EmployeeId";E={_.ExtensionProperty["employeeId"]}',
'DisplayName',
'Surname',
'givenName',
'UserPrincipalName',
'JobTitle',
'CompanyName'
'@{N="License":E={$_.ExtensionProperty["extension_a92a_msDS_cloudExtensionAttribute1"]}
)
Get-AzureADUser -Full $true -Filter 'accountEnabled eq true' | select $properties
}
}
Function Get-AllAzureADUsers {
process {
$users = @()
$users =+ Get-Users
$users | ForEach {
$manager = Get-AzureADUserManager -ObjectId $_.ObjectId | Select -ExpandProperty UserPrincipalName
[pscustomobject]@{
"Employee ID" = (Get-AzureADUser -ObjectID $_.ObjectId).ExtensionProperty["employeeId"]
"First Name" = $_.surname
"Last Name" = $_.givenName
"Work Email" = $_.UserPrincipalName
"Job Title" = $_.JobTitle
"Department" = $_.CompanyName
"Manager Email" = $manager
"License" = (Get-AzureADUser -ObjectId $_.ObjectId).ExtensionProperty["extension_a92a_msDS_cloudExtensionAttribute1"]
}
}
}
}
Get-AllAzureADUsers | Sort-Object Name | Export-CSV -Path $path -NoTypeInformation