timsstuff

Create-Mailboxes.ps1

Oct 23rd, 2015
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. [CmdletBinding()]
  2. param(
  3.     [Parameter(Mandatory=$True,Position=0)][string]$RootOU
  4. )
  5.  
  6. Import-Module ActiveDirectory
  7. if(!(Get-PSSnapin |
  8.     Where-Object {$_.name -eq "Microsoft.Exchange.Management.PowerShell.E2010"})) {
  9.       ADD-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
  10. }
  11.  
  12. $start = Get-Date
  13. $domain = Get-ADDomain
  14. $addomain = $domain.Forest
  15. $domaindn = $domain.DistinguishedName
  16. $logfile = ".\CreateMailboxes.log"
  17. $nl = "`r`n"
  18. $ou = "OU=Users,OU=$RootOU,$domaindn"
  19.  
  20. function writelog([string]$message) {
  21.     $timestamp = Get-Date
  22.     $fc = "White"
  23.     if($message.contains("ERROR")) {$fc ="Red"}
  24.     Add-content $logfile -value "$timestamp : $message"
  25.     Write-Host $message -ForegroundColor $fc
  26. }
  27.  
  28. writelog "Creating mailboxes in $ou at $start"
  29. Write-Host $nl
  30.  
  31. Get-ADUser -SearchBase $ou -LDAPfilter "(objectClass=user)" -properties DisplayName,SamAccountName,EmailAddress | ForEach-Object {
  32.     Set-Variable -Name testmb -Value $null -Scope 0
  33.     $username = $_.SamAccountName
  34.     $upn = $username + "@" + $addomain
  35.     $DisplayName = $_.DisplayName.Trim()
  36.     $DisplayName = $DisplayName.Replace("Contoso","Microsoft")
  37.     $testmb = Get-Mailbox $username -ErrorAction SilentlyContinue
  38.     if($testmb -eq $null) {
  39.         writelog "Creating mailbox $DisplayName"
  40.         Enable-Mailbox $username -DisplayName $DisplayName -Alias $username
  41.     }
  42.     else {
  43.         #writelog "Mailbox  $name already exists, skipping."
  44.     }
  45. }
  46.  
  47. $end = Get-Date
  48. $elapsed = $end - $start
  49. Write-Host $nl
  50. writelog "Finished import at $end ($elapsed)"
Advertisement
Add Comment
Please, Sign In to add comment