Recently I came across a new requirement from application team that may be unique to our enviornment but still sharing the code for everyone else to us.
Requirement is below:
- Report All employees except from vendor
- Report any new addition from previous report
- Report on PriomarySMTP modification as compare to previous report
- Report on any removal of emplooyees mailbox
- Report should check both Onpremise and Online world
Download and extract the script from below link that fulfills all the above criteria.
https://github.com/VikasSukhija/Downloads/blob/master/EmpFeedReport.zip
psfile: Previous file
Report: All 4 reports based on time stamp
EmpFeedReport.ps1: Actual powershell Code
State-Email.csv: State file created when you run it first time.
Update the Variables inside the .ps1 script:
########################################################
$limit = (Get-Date).AddDays(-60) #for report/logs rectention – Chnage the limit as per your requirement
$path1 = (Get-Location).Path + “\Logs”
$path2 = (Get-Location).Path + “\Report”
$path3 = (Get-Location).Path + “\Psfile”
$email1 = “VSukhija@labtest.com”
$email2 = “SSukhija@labtest.com”
$from = “DONotReply@labtest.com”
$smtpserver = “SMTP Server”
$collmbx = @()
$collection = @()
$collection1 = @()
$Statefile = “.\State-Email.csv”
$regex = ‘^\d+$’ #This is for matching integer i.e employee id
#########################################################
First we are fetching all mailboxes from onpremise and online enviornment where curtomattribute11 matches intreger and customattribute10 is not like vendor.
$collmbx = get-mailbox -resultsize unlimited -RecipientTypeDetails “UserMailbox” | where{ ($_.CustomAttribute11 -match $regex) -and ($_.CustomAttribute10 -notlike “Vendor”) } | select Name, Customattribute11, PrimarySMTPAddress
$collmbx += get-remotemailbox -resultsize unlimited | where{ ($_.CustomAttribute11 -match $regex) -and ($_.CustomAttribute10 -notlike “Vendor”) } | select Name, Customattribute11, PrimarySMTPAddressWrite-Host “—————————–” -ForegroundColor Green
Now , we will compare the fetched data with the old data that is in state file to find out changes , Additions and removals from last feed.
refer the separate sections inside the script that shows use of compare-object and other comparison operations.
Note: On first run only state file will be created & on next run only other reprts based on changes will get created.
Sharing the code, please modify as per your requirement to reuse it.
<# .NOTES =========================================================================== Created on: 12/8/2016 4:19 PM Updated on: 01/08/2018 Created by: Vikas Sukhija Organization: Filename: EmpfeedReport.ps1 =========================================================================== .DESCRIPTION This Script will send Report of Users to be added to BrainStorm Master/Incremental List of users #> ################Add Modules Exchange############################# $error.clear() If ((Get-PSSnapin | where { $_.Name -match "Microsoft.Exchange.Management.PowerShell.E2010" }) -eq $null) { Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 } ###############ADD Logs & Variables################################ $date1 = get-date -format d $date1 = $date1.ToString().Replace("/", "-") $time = get-date -format t $time = $time.ToString().Replace(":", "-") $time = $time.ToString().Replace(" ", "") $log = (Get-Location).Path + "\Logs" + "\" + "Processed_PS_Logs" + $date1 + "_" + $time + "_.log" $report1 = (Get-Location).Path + "\Report" + "\" + "Report_Modified" + $date1 + "_" + $time + "_.csv" $report2 = (Get-Location).Path + "\Report" + "\" + "Report_ADDS" + $date1 + "_" + $time + "_.csv" $report3 = (Get-Location).Path + "\Report" + "\" + "Report_Delete" + $date1 + "_" + $time + "_.csv" $report4 = (Get-Location).Path + "\Report" + "\" + "Report_Master" + $date1 + "_" + $time + "_.csv" $psfile = (Get-Location).Path + "\Psfile" + "\" + "Psfile" + $date1 + "_" + $time + "_.csv" $limit = (Get-Date).AddDays(-60) #for report recycling $path1 = (Get-Location).Path + "\Logs" $path2 = (Get-Location).Path + "\Report" $path3 = (Get-Location).Path + "\Psfile" $email1 = "VSukhija@labtest.com" $email2 = "SSukhija@labtest.com" $from = "DONotReply@labtest.com" $smtpserver = "SMTP Server" $collmbx = @() $collection = @() $collection1 = @() $Statefile = ".\State-Email.csv" $regex = '^\d+$' ################Email Function##################### function Send-Email { [CmdletBinding()] param ( $From, [array]$To, [array]$bcc, [array]$cc, $body, $subject, $attachment, $smtpserver ) $message = new-object System.Net.Mail.MailMessage $message.From = $from if ($To -ne $null) { $To | ForEach-Object{ $to1 = $_ $to1 $message.To.Add($to1) } } if ($cc -ne $null) { $cc | ForEach-Object{ $cc1 = $_ $cc1 $message.CC.Add($cc1) } } if ($bcc -ne $null) { $bcc | ForEach-Object{ $bcc1 = $_ $bcc1 $message.bcc.Add($bcc1) } } $message.IsBodyHtml = $True if ($subject -ne $null) { $message.Subject = $Subject } if ($attachment -ne $null) { $attach = new-object Net.Mail.Attachment($attachment) $message.Attachments.Add($attach) } if ($body -ne $null) { $message.body = $body } $smtp = new-object Net.Mail.SmtpClient($smtpserver) $smtp.Send($message) } ################################################################ if ($error) { Write-Host "Error in initialization"; Send-Email -To $email2 -From $from -subject "BrainStrom Report Script initialization failure" -smtpserver $smtpserver timeout 10; exit } Start-Transcript -path $log get-date ################ Collect All mailboxes########################### Write-Host "Fetching mailbox data Started" -ForegroundColor Green Write-Host "-----------------------------" -ForegroundColor Green $collmbx = get-mailbox -resultsize unlimited -RecipientTypeDetails "UserMailbox" | where{ ($_.CustomAttribute11 -match $regex) -and ($_.CustomAttribute10 -notlike "Vendor") } | select Name, Customattribute11, PrimarySMTPAddress $collmbx += get-remotemailbox -resultsize unlimited | where{ ($_.CustomAttribute11 -match $regex) -and ($_.CustomAttribute10 -notlike "Vendor") } | select Name, Customattribute11, PrimarySMTPAddress Write-Host "-----------------------------" -ForegroundColor Green Write-Host "Fetching mailbox data Finished" -ForegroundColor Green if ($error) { Write-Host "Error in Fetching mailboxes data from Exchnage"; Send-Email -To $email2 -From $from -subject "BrainStrom Report error fetching mailboxes" -smtpserver $smtpserver Stop-Transcript; timeout 10; exit } If (!(Test-Path $Statefile)) { $collmbx | select Name, Customattribute11, PrimarySMTPAddress | Export-csv $Statefile -NoTypeInformation } #########################Start comparison########################## $stcsv = import-csv $Statefile $coll = @() $Changes = Compare-Object $stcsv $collmbx -property Customattribute11, PrimarySMTPAddress | Select-Object customattribute11, PrimarySMTPAddress, @{ n = 'State'; e = { If ($_.SideIndicator -eq "=>") { "Current" } elseif ($_.SideIndicator -eq "<=") { "Previous" } else { "Ignore" } } } ############################Modifictations############################ if ($changes) { $Changes | foreach-object{ $mcoll = "" | select Name, customattribute11, PreviousSMTP, NewSMTP if ($_.state -eq "Previous") { $cus1 = $_.customattribute11 $Name = ($collmbx | where{ $_.customattribute11 -eq $cus1 }).name $PreviousSMTP = $_.PrimarySMTPAddress foreach ($chg in $Changes) { if (($cus1 -eq $chg.customattribute11) -and ($chg.state -eq "Current")) { $NewSMTP = $chg.PrimarySMTPAddress $mcoll.Name = $Name $mcoll.customattribute11 = $cus1 $mcoll.PreviousSMTP = $PreviousSMTP $mcoll.NewSMTP = $NewSMTP } } } $collection += $mcoll } $collection1 = $collection | where{ $_.name -ne $null } if ($collection1) { #$collection1 $tcoll = $null $tcollection = @() $collection1 | ForEach-Object{ $tcoll = "" | select Department, Name, OldEmail, NewEmail, FirstName, LastName, Title, SystemGroup, UserGroup $user = $null $user = get-user $_.Name $tcoll.Department = $user.department $tcoll.Name = $_.Name $tcoll.OldEmail = $_.PreviousSMTP $tcoll.NewEmail = $_.NewSMTP $tcoll.FirstName = $user.FirstName $tcoll.LastName = $user.LastName $tcoll.Title = $user.Title $tcoll.SystemGroup = "All LAB" $tcoll.UserGroup = "" $tcollection += $tcoll } $tcollection | Export-Csv $report1 -NoTypeInformation } } ###########################Additions######################################## $mcoll = $null $difference = $null $collection = @() $collection1 = @() if ($changes) { $current = $Changes | where{ $_.state -eq "Current" } | select -expand customattribute11 $previous = $stcsv | select -expand customattribute11 $difference = @() $current | ForEach-Object{ if ($previous -notcontains $_) { $difference += $_ } } $difference | ForEach-Object{ $cus1 = $_ $mcoll = "" | select Name, customattribute11, SMTP $diffmbx = ($collmbx | where{ $_.customattribute11 -eq $cus1 }) $mcoll.Name = $diffmbx.Name $mcoll.customattribute11 = $diffmbx.customattribute11 $mcoll.SMTP = $diffmbx.PrimarySMTPAddress $collection += $mcoll } $collection1 = $collection | where{ $_.name -ne $null } if ($collection1) { #$collection1 $tcoll = $null $tcollection = @() $collection1 | ForEach-Object{ $tcoll = "" | select Department, Name, Email, FirstName, LastName, Title, SystemGroup, UserGroup $user = $null $user = get-user $_.Name $tcoll.Department = $user.department $tcoll.Name = $_.Name $tcoll.Email = $_.SMTP $tcoll.FirstName = $user.FirstName $tcoll.LastName = $user.LastName $tcoll.Title = $user.Title $tcoll.SystemGroup = "All LAB" $tcoll.UserGroup = "" $tcollection += $tcoll } $tcollection | Export-Csv $report2 -NoTypeInformation } } ##################################Removal#################################### $mcoll = $null $collection = @() $collection1 = @() if ($changes) { $current = $collmbx | select -expand customattribute11 $previous = $stcsv | select -expand customattribute11 $difference = Compare-Object $collmbx $stcsv $previous | ForEach-Object{ if ($current -notcontains $_) { $difference += $_ } } $difference | ForEach-Object{ $cus1 = $_ $mcoll = "" | select Name, customattribute11, SMTP $diffmbx = ($stcsv | where{ $_.customattribute11 -eq $cus1 }) $mcoll.Name = $diffmbx.Name $mcoll.customattribute11 = $diffmbx.customattribute11 $mcoll.SMTP = $diffmbx.PrimarySMTPAddress $collection += $mcoll } $collection1 = $collection | where{ $_.name -ne $null } if ($collection1) { #$collection1 $tcoll = $null $tcollection = @() $collection1 | ForEach-Object{ $tcoll = "" | select Department, Name, Email, FirstName, LastName, Title, SystemGroup, UserGroup $user = $null $user = get-user $_.Name $tcoll.Department = $user.department $tcoll.Name = $_.Name $tcoll.Email = $_.SMTP $tcoll.FirstName = $user.FirstName $tcoll.LastName = $user.LastName $tcoll.Title = $user.Title $tcoll.SystemGroup = "All LAB" $tcoll.UserGroup = "" $tcollection += $tcoll } $tcollection | Export-Csv $report3 -NoTypeInformation } } ############################################################################# Copy-Item $Statefile $psfile timeout 5 $collmbx | Export-Csv $Statefile -NoTypeInformation # new state ##########################Full Feed######################################## $mcoll = $null $collection = @() $collection1 = @() if ($collmbx) { #$collection1 $tcoll = $null $tcollection = @() $collmbx | ForEach-Object{ $tcoll = "" | select Department, Name, Email, FirstName, LastName, Title, SystemGroup, UserGroup $user = $null $user = get-user $_.Name | select Department, FirstName, LastName, Title $tcoll.Department = $user.department $tcoll.Name = $_.Name $tcoll.Email = $_.PrimarySmtpAddress $tcoll.FirstName = $user.FirstName $tcoll.LastName = $user.LastName $tcoll.Title = $user.Title $tcoll.SystemGroup = "All LAB" $tcoll.UserGroup = "" $tcollection += $tcoll } } $tcollection | Export-Csv $report4 -NoTypeInformation if ($error) { Send-Email -To $email2 -From $from -subject "Email Address Change error Report" -body $Error -smtpserver $smtpserver } if (Test-Path $report1) { Send-Email -To $email1 -bcc $email2 -From $from -subject "BrainStorm Feed Modfified Report" -attachment $report1 -smtpserver $smtpserver } if (Test-Path $report2) { Send-Email -To $email1 -bcc $email2 -From $from -subject "BrainStorm Feed ADD Report" -attachment $report1 -smtpserver $smtpserver } if (Test-Path $report3) { Send-Email -To $email1 -bcc $email2 -From $from -subject "BrainStorm Feed Delete Report" -attachment $report1 -smtpserver $smtpserver } if (Test-Path $report4) { Send-Email -To $email1 -bcc $email2 -From $from -subject "BrainStorm Feed Master Report" -attachment $report1 -smtpserver $smtpserver } #######################Recycle####################### Get-ChildItem -Path $path1 | Where-Object { $_.CreationTime -lt $limit } | Remove-Item -recurse -Force Get-ChildItem -Path $path2 | Where-Object { $_.CreationTime -lt $limit } | Remove-Item -recurse -Force Get-ChildItem -Path $path3 | Where-Object { $_.CreationTime -lt $limit } | Remove-Item -recurse -Force get-date Stop-Transcript
Thanks for Reading
Vikas Sukhija