Category Archives: Powershell Exchange

Clean up user accounts in one OU after linked-mailbox migration to new domain

This script uses the Quest AD Cmdlets that can be downloaded free from Quest.

# Add the Quest commandlets if not added 
if(!(Get-PSSnapin | 
    Where-Object {$_.name -eq "quest.activeroles.admanagement"})) {
      ADD-PSSnapin Quest.Activeroles.ADManagement
    }

# Add Exchange 2010 commandlets (if not added)
if(!(Get-PSSnapin | 
    Where-Object {$_.name -eq "Microsoft.Exchange.Management.PowerShell.E2010"})) {
      ADD-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
    }

################## SETTINGS
# Home directory for users
$homedir = "\contoso.comusers"

# Domain
$domain = "contoso.com"

# Email address to keep
$keepmail = "@contoso.com"

# The OU we are working on
$OU = "contoso.com/Users/migrated_users"
##################

# Run on all users in the defined OU
Get-QADUser -SearchRoot $OU | 
foreach {
    echo "-------------------------------------------------"    
    echo "Working on $($_.displayname)"
    echo "-------------------------------------------------"

    # Generate username after the 3+3 rule
    $userprincipalname = ($_.firstname.substring(0,3) + $_.lastname.substring(0,3)).tolower()
    $userprincipalname = $userprincipalname.replace("ø","o")
    $userprincipalname = $userprincipalname.replace("å","a")
    $userprincipalname = $userprincipalname.replace("æ","e")
 
    # Make the changes on the user account
    Set-QADUser -Identity $_ -UserPrincipalName $($userprincipalname + "@" + $domain) -SamAccountName "$($userprincipalname)" -HomeDirectory $($homedir + $userprincipalname) -HomeDrive "H:"  #-whatif

    # Check to see if the users homedirectory exists
    if ( !(Test-Path -Path "$homedir$userprincipalname" -PathType Container) ) {

         # Doesn't exist so create it.
         Write-Host "home directory doesn't exist. Creating home directory."

         # Create the directory
         New-Item -path $homedir -Name $userprincipalname -ItemType Directory
         $userDir = "$homedir$userprincipalname"

         # Modify  Permissions on homedir
         $Rights= [System.Security.AccessControl.FileSystemRights]::Read -bor [System.Security.AccessControl.FileSystemRights]::Write -bor [System.Security.AccessControl.FileSystemRights]::Modify -bor [System.Security.AccessControl.FileSystemRights]::FullControl
         $Inherit=[System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit
         $Propogation=[System.Security.AccessControl.PropagationFlags]::None
         $Access=[System.Security.AccessControl.AccessControlType]::Allow
         $AccessRule = new-object System.Security.AccessControl.FileSystemAccessRule("$userprincipalname",$Rights,$Inherit,$Propogation,$Access)
         $ACL = Get-Acl $userDir
         $ACL.AddAccessRule($AccessRule)
         $Account = new-object system.security.principal.ntaccount($userprincipalname)
         $ACL.setowner($Account)
         $ACL.SetAccessRule($AccessRule)
         Set-Acl $userDir $ACL
    }

    # We need some sleep...
    start-sleep -sec 20

    # Now we need to clean up the users Exchange account
    Get-Mailbox -Identity $userprincipalname |
    
    # Loop through all the emailaddresses
    foreach { 
       $a = $_.emailaddresses
       $b = $_.emailaddresses
     
     # Remove all but $keepmail
       foreach($e in $a) 
           { 
           if ($e.tostring() -notmatch $keepmail ) 
               { $b -= $e; } 
           $_ | Set-mailbox -EmailAddressPolicyEnabled $false -emailaddresses $b -alias $userprincipalname
           }
    }
    
    # We had to remove the emailaddresspolicy to make changes. Let's reactivate it
    Set-mailbox -Identity $userprincipalname -EmailAddressPolicyEnabled $true
}

Delete all email addresses but one on a mailbox

  Get-Mailbox -Identity $userprincipalname |
    
    # Loop through all the emailaddresses
    foreach { 
       $a = $_.emailaddresses
       $b = $_.emailaddresses
     
     # Remove all but $keepmail
       foreach($e in $a) 
           { 
           if ($e.tostring() -notmatch $keepmail ) 
               { $b -= $e; } 
           $_ | Set-mailbox -EmailAddressPolicyEnabled $false -emailaddresses $b -alias $userprincipalname
           }
    }
    
    # We had to remove the emailaddresspolicy to make changes. Let's reactivate it
    Set-mailbox -Identity $userprincipalname -EmailAddressPolicyEnabled $true
}

Create mailbox to all users in a CSV based on the 3+3 naming policy

# Create mailbox to all users in a CSV based on the 3+3 naming policy.
# This will also create the user in AD
$parentcontainer = "contoso.com/container"
$homedirectory = "contoso.comusers$username"

# Prompt the user for password
$password = Read-Host "Enter password" -AsSecureString

# The following has to be done to import with european characters
cat "c:tempusers.csv" > c:templisttemp.csv

# Loop through the list and 
# - replace european letters with o,a or e.
# - create username based on the 3+3 naming convention 
#   (three first letters in the firstname and lastname.)
# - all lower case
import-csv c:templisttemp.csv | foreach {
    $username = ($_.firstname.substring(0,3) + $_.lastname.substring(0,3)).tolower()
    $username = $username.replace("ø","o")
    $username = $username.replace("å","a")
    $username = $username.replace("æ","e")
    
# The following line can create the user if you do not need mailbox.
#    new-qadUser -ParentContainer $parentcontainer -FirstName $_.firstname -LastName $_.lastname -DisplayName $($_.FirstName + " " + $_.LastName) -SamAccountName $username -Name $username -UserPrincipalName ($username + '@contoso.com') -whatif

# Create the mailbox
    New-Mailbox -Alias $username -Name $($_.FirstName + " " + $_.LastName) -OrganizationalUnit $parentcontainer -UserPrincipalName ($username + '@contoso.com') -SamAccountName $username -FirstName $_.firstname -LastName $_.lastname -ResetPasswordOnNextLogon $false -password $password -whatif
}

Adding snapins/modules to PowerShell

# Import the ActiveDirectory cmdlets
Import-Module ActiveDirectory

# List available snapins on your system:
Get-PSSnapin

# List registered snapins
Get-PSSnapin -Registered

# Alias:
gsnp

# Add Snapin:
Add-PSSnapin

# Examples:
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin # Exchange 2007
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 # Exchange 2010
Add-PSSnapin Microsoft.SystemCenter.VirtualMachineManager # WMM (Hyper-V)
Add-PSSnapin Quest.Activeroles.ADManagement # Quest commandlets

(You can download the Quest Commandlets from <a href="# Install from http://www.quest.com/powershell/activeroles-server.aspx&#8221; title=”# Install from http://www.quest.com/powershell/activeroles-server.aspx“>here.)

You will get an error if you try to add a snapin that is already added. Your script will continue to run but you’ll have a bunch of nasty red letters in your shell. Not too sexy, eh? The way to avoid this is to first check if the snapin is loaded and then only load if it is not.
Do it like this:

# Add Exchange 2007 commandlets (if not added)
if(!(Get-PSSnapin | 
    Where-Object {$_.name -eq "Microsoft.Exchange.Management.PowerShell.Admin"})) {
      ADD-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
    }

# Add Exchange 2010 commandlets (if not added)
if(!(Get-PSSnapin | 
    Where-Object {$_.name -eq "Microsoft.Exchange.Management.PowerShell.E2010"})) {
      ADD-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
    }

# Add Virtual Machine Manager (Hyper-V) commandlets (if not added)
if(!(Get-PSSnapin | 
    Where-Object {$_.name -eq "Microsoft.SystemCenter.VirtualMachineManager"})) {
      ADD-PSSnapin Microsoft.SystemCenter.VirtualMachineManager
    }

# Add Quest commandlets (if not added)
if(!(Get-PSSnapin | 
    Where-Object {$_.name -eq "Quest.Activeroles.ADManagement"})) {
      ADD-PSSnapin Quest.Activeroles.ADManagement
    }

Head on over to http://blogs.technet.com/b/heyscriptingguy/archive/2010/10/16/learn-how-to-load-and-use-powershell-snap-ins.aspx to learn more about snapins.