Staff Off-Boarding with Office 365

office-365

Over time in any environment the day will come around when the inevitable happens and staff leave. This happens due to lots of different reasons but there is often a question as to what to do with user accounts when this happens. This is particularly true in smaller companies with no set process for IT departments off-boarding staff.

In my own environment, I decided to set up a standard script which would work with Active Directory and Office 365 to achieve the following;

  1. Connects to your local DC for active directory functions and Office 365 for mailbox functions
  2. Disable the employee’s user account (verifies the user details before proceeding)
  3. Stamp details on the disabled user account with the IT person who disabled the account for audit purposes
  4. Move the disabled user account to a separate OU
  5. Disable all forms of remote mail access (OWA, ActiveSync, POP, etc)
  6. Set an Out of Office stating that the employee has left the company
  7. Place the mailbox into Legal hold for data retention purposes
  8. Hides the account from the GAL
  9. Emails the former employee’s manager advising that the account has been disabled

The user account is then maintained for a period of 30 days before being deleted and thus returning any assigned Office 365 licenses to the pool etc.

This might help to give you some ideas about setting up your own scripting process for dealing with this issue.

Script Download Link – https://gallery.technet.microsoft.com/scriptcenter/Staff-Off-Boarding-Script-430bdd0a


<#
.NOTES
===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.2.128
Created on: 04/11/2016 21:00
Created by: Maurice Daly
Filename: DisableUserOffice365.ps1
===========================================================================
.DESCRIPTION
This script provides a standard off-boarding method for staff leaving
the company.

The script does the following;
1. Disables the specified user account
2. Updates the user description with the user who disabled the account
and the time/date when the account was disabled
3. Moves the account to the disabled user account OU (needs to exist)
4. Sets an out of office reply stating that the employee has left the company
5. Disables activesync, pop3, imap etc
6. Places mail account into legal hold for 7 years (requires Office 365 E3)
7. Hides the mail account from the GAL
8. Emails the former employee's manager advising that the account has been disabled

Version 1.0
Initial release

Use : This script is provided as it and I accept no responsibility for
any issues arising from its use.

Twitter : @modaly_it
Blog : https://modalyitblog.wordpress.com/
#>

Write-Host " **************** PLEASE ENTER ACTIVE DIRECTORY ADMIN CREDENTIALS **************** "
$Credential = Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME"
$DC = $env:LOGONSERVER.Substring(2)

#Initiate Remote PS Session to local DC
$ADPowerShell = New-PSSession -ComputerName $DC -Authentication Negotiate -Credential $Credential

# Import-Module ActiveDirectory
write-host "Importing Active Directory PowerShell Commandlets"
Invoke-Command -Session $ADPowerShell -scriptblock { import-module ActiveDirectory }
Import-PSSession -Session $ADPowerShell -Module ActiveDirectory -AllowClobber -ErrorAction Stop

# Retrieve AD Details
$ADDetails = Get-ADDomain
$Domain = $ADDetails.DNSRoot
Clear-Host

write-host "Importing Office 365 PowerShell Commandlets"
Write-Host -ForegroundColor White -BackgroundColor DarkBlue " **************** PLEASE ENTER OFFICE 365 ADMIN CREDENTIALS **************** "
$Office365Credential = Get-Credential
$Office365PowerShell = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Office365Credential -Authentication Basic -AllowRedirection
Import-PSSession $Office365PowerShell
Clear-Host

write-host " **************** Disable Active Directory User Account & Enable Out Of Office **************** "
write-host " "

# Get Variables
$DisabledDate = Get-Date
$LeaveDate = Get-Date -Format "dddd dd MMMM yyyy"
$DisabledBy = Get-ADUser "$env:username" -properties Mail
$DisabledByEmail = $DisabledBy.Mail

# Prompt for AD Username
$Employee = Read-Host "Employee Username"
$EmployeeDetails = Get-ADUser $Employee -properties *
If ($EmployeeDetails.Manager -ne $null)
{
$Manager = Get-ADUser $EmployeeDetails.Manager -Properties Mail
}

Clear-Host

# Prompt for confirmation
write-host " ******************************** CONFIRM USER DISABLE REQUEST ******************************** "
write-host " "
write-host -ForegroundColor Yellow "Please review the Employee details below to ensure you are disabling the correct user account."
$EmployeeDetails | fl Name, Title, Company, @{ Expression = { $_.mail }; Label = "Email Address" }, @{Expression = { $_.Created }; Label = "Employment Started"}

$choice = " "
while ($choice -notmatch "[y|n]")
{
$choice = read-host "Do you want to continue? (Y/N)"
}

# Actions
if ($choice -eq "y")
{
Clear-Host
write-host " ******************************** DISABLING USER ACCOUNT ******************************** "
write-host " "
write-host "Step1. Modifying user description for audit purposes" -ForegroundColor Yellow
Set-ADUser $Employee -Description "Disabled by $($DisabledBy.name) on $DisabledDate"
write-host "Step2. Disabling $Employee Active Directory Account." -ForegroundColor Yellow
Disable-ADAccount $Employee
write-host "Step3. Moving $Employee to the Disabled User Accounts OU." -ForegroundColor Yellow
write-host " "
Move-ADObject -Identity $EmployeeDetails.DistinguishedName -targetpath "OU=Disabled User Accounts,DC=YOURDOMAIN,DC=SUFFIX"
write-host "Waiting 5 seconds for AD & Exchange OU update to complete"
sleep -Seconds 5
write-host " "
write-host "Refreshing Employee Details for Exchange Modification."
write-host " "
Get-ADUser $Employee -Properties Description | Format-List Name, Enabled, Description
write-host "Step 4. Setting Exchange Out Of Office Auto-Responder." -ForegroundColor Yellow
Set-MailboxAutoReplyConfiguration -Identity $EmployeeDetails.Mail -AutoReplyState enabled -ExternalAudience all -InternalMessage "Please note that I no longer work for $($EmployeeDetails.company) as of $LeaveDate." -ExternalMessage "Please note that I no longer work for $($EmployeeDetails.company) as of $LeaveDate. Direct all correspondence to info@yourdomain.suffix."
Write-Host "Step 5. Disabling POP,IMAP, OWA and ActiveSync access for $User" -ForegroundColor Yellow
Set-CasMailbox -Identity $EmployeeDetails.mail -OWAEnabled $false -POPEnabled $false -ImapEnabled $false -ActiveSyncEnabled $false
Write-Host "Step 6. Placing mailbox $($EmployeeDetails.name) into Ligitgation hold for 7 years" -ForegroundColor Yellow
Set-Mailbox -Identity $EmployeeDetails.mail -LitigationHoldEnabled $true -LitigationHoldDuration 2555
Write-Host "Step 7. Hiding $($EmployeeDetails.name) from Global Address lists" -ForegroundColor Yellow
Set-ADUser -identity $Employee -add @{ msExchHideFromAddressLists = "True" }
Set-ADUser -instance $EmployeeDetails -whatif
If ($Manager.Mail -like "*@*")
{
Write-Host "Step 8. Sending Confirmation E-mail To Employee's Manager." -ForegroundColor Yellow
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("youroffice365mailserveraddress")
$msg.From = "Support@yourdomain.suffix"
$msg.To.Add("$($Manager.Mail)")
$msg.subject = "IT Notification - Employee Leaver Confirmation"
$msg.body = "This email is confirm that $($EmployeeDetails.Name)'s account has been disabled. An out of office notification advising that $($EmployeeDetails.Name) has left the company has also been set. Note that the account will be deleted after 30 days."
$smtp.Send($msg)
}
}else{
write-host " "
write-host "Employee disable request cancelled" -ForegroundColor Yellow
}

 

Enabling Focused Inbox – Office 365

As you might be aware Microsoft is introducing a new feature in Office 365 called Focused mailbox. The new feature is effectively replacing the clutter inbox that we have become familiar with, but also adds new features such as the ability to highlight people in the body of an email with the use of the @ symbol in front of the person.

More details can be found @ https://support.office.com/en-ie/article/Focused-Inbox-for-Outlook-f445ad7f-02f4-4294-a82e-71d8964e3978

Microsoft are currently in the process of rolling this out, if however you get itchy feet and want to enable the feature yourself simply run the PowerShell command below.
Note that I would not recommend this feature for Shared mailboxes, but if you want to go ahead just remove the filter.

Enable Focused Mail for Your Office 365 Tenant

$UserCredential = Get-Credential -Message "Office 365 Administrator Account Login"
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session
Set-OrganizationConfig -FocusedInboxOn $True

Enable Focused Mail for All Users

$UserCredential = Get-Credential -Message "Office 365 Administrator Account Login"
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session
Get-Mailbox | Where-Object {$_.RecipientTypeDetails -ne "SharedMailbox"} | Set-FocusedInbox -FocusedInboxOn $True


Update : 5/10/2016

Microsoft have delayed the roll-out of this feature, you can still prepare your mailboxes for the focused feature but your Office 365 tenant will need to be focused enabled by Microsoft.

Jetze Mellema has a blog post on this – http://jetzemellema.blogspot.ie/2016/10/focused-inbox-for-outlook-is-delayed.html?spref=tw

Update : 15/11/2016

I logged onto OWA this evening and finally focused mailbox has been enabled on our tenant 🙂

focused

focused2

 

Office365 – Listing all members of both static and dynamic distrubiton groups

Here is a nice little script that connects to your Office365 environment, reads the contents of all distribution groups both static and dynamic and exports the filtered contents into a CSV file thus allowing you to apply filters etc in Excel.


<#
    .NOTES
    ===========================================================================
     Created with:     SAPIEN Technologies, Inc., PowerShell Studio 2015 v4.2.85
     Created on:       12/06/2015 9:47 a.m.
     Created by:       Maurice Daly
     Filename:     GetDistributionGroupMembers.ps1
    ===========================================================================
    .DESCRIPTION
        List all members of all static and dynamic distribution groups from your
        Office 365 portal and export the contents into a CSV.
#>

$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session

$DistributionGroups = Get-DistributionGroup
$DynDistributionGroups = Get-DynamicDistributionGroup

$FilePath = "C:\DistributionGroupMembers.csv"

# Read Static Distribution Groups
foreach ($DistributionGroup in $DistributionGroups) {
    Get-DistributionGroupMember $DistributionGroup.PrimarySMTPAddress | Sort-Object name | Select-Object @{ Label = "Distribution Group"; Expression = { $DistributionGroup.name } }, Name | Export-Csv -Path $FilePath -Delimiter ";" -NoTypeInformation -Append -Force
}

# Read Dynamic Distribution Groups
foreach ($DynDistributionGroup in $DynDistributionGroups)
{
    Get-Recipient -RecipientPreviewFilter $DynDistributionGroup.RecipientFilter | Sort-Object name | Select-Object @{ Label = "Distribution Group"; Expression = { $DynDistributionGroup.name } }, Name | Export-Csv -Path $FilePath -Delimiter ";" -NoTypeInformation -Append -Force
}

# Close Remote PS Session
Get-PSSession | Remove-PSSession

Azure AD SSO in a non-ADFS environment – Windows 10

In a world without ADFS.. Single Sign On is possible..

Having made the migration from onsite Exchange and SharePoint to Office 365 in early 2015 one of the key issues that users had was the lack of single sign on facilities to applications based in the cloud. You might ask why didn’t you use ADFS for your implementation, well I like many SME systems admins had made a conscious decision to run with DirSync as this lowered the overall foot print of our hybrid set up, I also liked the idea that even in the event of a complete loss of internal resources the Office 365 cloud would still allow employees to authenticate.

In my case the decision was concreted only after speaking with Microsoft Office 365 speakers and product development engineers, as their view was unless you have a specific reason for using ADFS then the DirSync product road map with the migration to Azure AD Connect would be more than sufficient for my needs. I convinced my manager and the migration went ahead..

So to fast forward to today and with the improvements in the ability to sync details to and from Azure Active Directory without an ADFS environment I am going to run through one of the newer authentication features of Windows 10, this being Azure AD SSO on domain joined devices.

Single Sign On without ADFS.. What Is This Black Magic???

The ability to open cloud based resources which integrate with Azure Active Directory without having to sign on again has been the domain of ADFS up until this point. With the latest release of Azure AD Connect and Windows 10 1511 on-wards however we can now achieve a similar experience.

The system works by issuing authentication tokens when registering the physical device of the user. Further in depth technical info is available on TechNet – https://blogs.technet.microsoft.com/enterprisemobility/2016/02/17/azure-ad-domain-join-windows-10/

So How Do I Implement It?

The implementation process is very straight forward;

  1. Enable users to join devices to Azure AD

    Log onto the Azure Admin Portal, open your tenant and click on the Configure tab. Scroll down to the Devices section and apply either a selected or all device configuration depending on your security requirements. Example screenshots below;

  2. Download and install the latest version of Azure AD Connect from https://www.microsoft.com/en-us/download/details.aspx?id=47594.azureaddownloadNote if you are still using DirSync or Azure AD Sync, you should migrate to Azure AD Connect before the 13th of April 2017 as support will be deprecated at that point. The upgrade process from these old legacy tools is very straight forward during the setup wizard.
  3. Ensure your Windows 10 clients are compatible

    Windows 10 build 1511 (November 2015) onwards support Azure AD SSO device join via group poilcy. If you are running the RTM build 10240, you will need to upgrade first.To check this either open a command prompt and read the Windows version on the second line or open PowerShell and type;

    (Get-WmiObject win32_operatingsystem).version

    checkwindowsversion

    For those of you using SCCM, I suggest you create a collection based on the version of Windows 10 for management purposes. The following query will add clients running build 1607 to your collection;

    select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_OPERATING_SYSTEM on SMS_G_System_OPERATING_SYSTEM.ResourceID = SMS_R_System.ResourceId where SMS_G_System_OPERATING_SYSTEM.BuildNumber = “14393”


  4. Update Your Central Store – Group Policy Administrative Templates In order to enable this feature you will need to ensure that your group policy administrative templates are up to date. The latest Windows 10 templates can be downloaded from the following link – https://www.microsoft.com/en-us/download/details.aspx?id=53430azureadtemplates
  5. Enable Device Sync – Azure AD Connect

    Now we have to enable device synchronization with Azure AD. There are two ways to achieve this, you can either run the Azure AD Connect wizard or edit the connectors yourself. In the below example I am going to go with the later;

    • On your Azure AD Connect server, open the Synchronization Service Managersyncscreen1Right-click on the Connectors button and right click on the Active Directory Domain Services and to to Properties
    • Configure Directory Partitions Click on Configure Directory Partitions and then click on the Containers button.syncscreen2
      When prompted enter an account with sufficient rights to Active Directory.
    • Select Computer OU to Sync Browse through your Active Directory and select the OU’s which contain computer accounts you wish to synchronize to Azure AD for the purpose of using Azure SSO.

      syncscreen3

    • Force Full Synchronization

      Right click on your Active Directory Domain Services connector and click on Run.

      syncscreen4

      On this screen click on the Full Import button. Once this job has completed do the same for the Windows Azure Active Directory connector.

  6. Configure GPO Settings

    Open Group Policy Management Editor and either create a new GPO or modify an existing one which applies settings to computers within the OU’s you have set to sync.

    Open the Computer Settings\Policies\Administrative Templates\Windows Components\Device Registration folderClick on the Register Domain Joined Computers As Devices setting and click Enable.

    GPODeviceReg.jpg

  7. Have Patience…There will obviously be delay between devices refreshing their GPO policies, Azure AD Sync times and devices registering.
  8. Verifying Device Sync Status

    Download the Microsoft Azure Active Directory Module for Windows PowerShell from the following link : https://azure.microsoft.com/en-us/documentation/articles/powershell-install-configure/Open a Azure AD Module PS window and connect to your Azure tenant environment by typing;

    Connect-MsolService
    


    azurepsconnect

    Once connected type the following to display a full list of registered devices and their current state;

    Get-MsolDevice -All | FT DisplayName, DeviceOS*, DeviceTrust*
    


    adpslist

    You can also run the following PS command to get a count of machines registered and compare this to your SCCM collection;

    (Get-MsolDevice -All).Count
    


Its Done..

Once your devices are successfully registered, your users should be automatically signed into their Azure AD cloud services. Now you have another little win for making their lives that bit easier without going to the extent of implementing a full ADFS environment.
Update – 29/9/2016

With the latest 16.0.7341.2035 build of Office 2016, SSO is now fully functional when opening Outlook. The below screen is now presented to the user rather than the usual Add Account wizard which prompts you for your password at the end. Now all the user has to do is click Connect and the settings download & sign in happens in the background in the initial launch;

outlook

 

 

Office 365 Online Archive Error – Failed to enable the new cloud archive

A couple of days ago I came across a strange issue whilst updating our archive directory contact details. A couple of our user updates did not reflect in the global address book in our Office 365 hybrid environment. I logged onto our domain controller and the details where correct, so I then logged into Azure Active Directory (as we are using Direction Sync) and found that the details pulled back from Azure were also correct, so what was the issue?.

When I opened the user properties in the Office 365 console I received the following error message:

“Exchange: Failed to enable the new cloud archive xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxx of mailbox xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxx because a different archive xxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxx exists. To enable the new archive, first disable the archive on-premises. After the next Dirsync sync cycle, enable the archive on-premises again.
Exchange: An unknown error has occurred. Refer to correlation ID: c0e37858-6d41-423a-b0bd-7d9bec686457″
So the issue was obviously related to a mailbox move that took place whereby the offline archive link was broken. So I used the Azure Active Directory PS (download from https://azure.microsoft.com/en-us/documentation/articles/powershell-install-configure/) and connected again to my Azure environment to check the health properties of my users.
To do this run the following PS commands
Connect-MSOLService
Get-MSOLUser | Sort-Object DisplayName | ft DisplayName, ValidationStatus
This will return the full list of Office 365 enabled user accounts and their status. Narrowing this down with the following command will display a list of users with validation errors;
Get-MSOLUser | Where-Object {$_.ValidationStatus -eq "Error"} | Sort-Object DisplayName | ft DisplayName, ValidationStatus
Once you have the list of users with errors it is time to get their online archive information to compare against the details from Exchange. First lets retrieve the Archive GUID by running the following script in an Office365 PowerShell environment;
Get-Mailbox "user identity with error status" | ft Name, ArchiveGuid
Now switching over to our Exchange PS console I ran the following script to check what archive details matched;
Get-RemoteMailbox -Identity "user identity with error status" | fl DisplayName, ArchiveGuid
Comparing the two ArchiveGuid values presented the cause of the issue. During a routine mailbox move the ArchiveGuid value had not been updated to the current version.
I resolved this by running the following process;
1. Update the remote mailbox properties with the ArchiveGuid value obtained from Azure AD;
– Set-RemoteMailbox -Identity  “user identity with error status” –ArchiveGuid “Guid value from Azure AD”
2. Run a full directory sync in DirSync
3. Run Start-OnlineCoexistenceSync PS command:
On your DirSync server –
PS:\Import-Module DirSync
PS:\Start-OnlineCoexistenceSync
Now wait a few minutes, go back into your Office 365 portal and the issue should be resolved 🙂

Scripting Your Office 2010 Removal – Office 365 Click To Run Migration

Like many small and medium sized companies the temptation to move to the cloud for services such as Exchange, Lync & SharePoint aka Office 365, makes both financial and resourcing sense. Given that the company I work for had decided to make the move I was tasked with the upgrade process of Office 2010 to the Office 2013/365 click to run version.

My initial though was to use a PowerShell script calling WMI to find the MSIExec, such as;

Get-WmiObject -Class Win32_product | Where-Object { $_.name -like “Microsoft Office Professional Plus 2010” }

I would then use the returned Identifying number combined with MSIExec switches to uninstall the product, however Office 2010 creates multiple uninstall command lines for each of its individual products.

With that option ruled out I was now on to using the Office setup.exe installer combined with customised XML to remove the product, which in theory is the easiest thing to do as the product will in 99% of cases remove Office without fault. In this scenario you use the following command (assuming you are using Pro Plus) : setup.exe /uninstall  ProPlus /config “path-to-xml”

My XML consists of the following:

<Configuration Product=”ProPlus”>
<Display Level=”none” CompletionNotice=”no” SuppressModal=”yes” AcceptEula=”yes” />
<Setting Id=”SETUP_REBOOT” Value=”Never” />
</Configuration>

The only issue I had with this method of uninstalling the product was the 1% rule where Office would simply refuse to uninstall. Microsoft provide a VBScript for such instances (http://blogs.technet.com/b/odsupport/archive/2011/04/08/how-to-obtain-and-use-offscrub-to-automate-the-uninstallation-of-office-products.aspx) and again I thought this would be a simple process of calling the VBScript from within a PowerShell script deployed by SCCM.

I added lines to run CScript and call the OffScrub10.vbs script but this resulted in the following error in the output log – Insufficient registry access permissions – exiting. So after many attempts I found that the most simple way to allow the script to run without compromising the security of your estate by lowering UAC settings is to copy the CScript.exe, rename it to CScript-Admin.exe and set the exe to run with administrative rights via the registry:

REG ADD “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers” /v $CSCriptLocation /t REG_SZ /d “RUNASADMIN” /f

After putting all of these steps together and also allowing for the removal of the Lync 2010 client, I created the following PowerShell script to remove your Office 2010 installation and also remove all email profiles from the local machine to avoid any PRF deployment issues when moving from your on-premise Exchange to Office 365. Simply put this script into your “Run Another Program First” section of your Office click to run installer in SCCM and automate the full removal and install of your new Office software.

Update – 20/2/2015 – Added 32/64 bit detection. Note you will need to copy the CScript.exe from both platforms and rename accordingly.

Script Download Link – https://gallery.technet.microsoft.com/Office-2010-365-Click-to-ef940429

Update – Microsoft appear to have pulled the OffScrub10.vbs script from their site. I have uploaded a copy to the Microsoft Script Library page in the above link.

<#
 .NOTES
 ===========================================================================
  Created with:  SAPIEN Technologies, Inc., PowerShell Studio 2014 v4.1.74
  Created on:    16/02/2015 12:30
  Created by:    Maurice Daly
  Filename:
 ===========================================================================
 .DESCRIPTION
  Office 2010 & Lync 2010 Clean Up Script. Use at your own risk.
#>

# Office 2010 Uninstall Files
$Office2010Tools = "\\YOURSERVER\YOURSHARE\YOURDIRECTORY"

# Check if Lync 2010 is installed
$Lync2010Installed = Get-WmiObject -Class Win32_product | Where-Object { $_.name -like "Microsoft Lync 2010*" }

# Uninstall Lync 2010 if detected
If ($Lync2010Installed -ne $null)
{
 $LyncArgs = "/X" + $Lync2010Installed.IdentifyingNumber + " /passive"
 Start-Process msiexec.exe -ArgumentList $LyncArgs -Wait
}

# Copy Office 2010 tools to Windows Temp
Get-ChildItem -Path $Office2010Tools | Copy-Item -Destination "C:\Windows\Temp"

# CScript location variable
If ((Test-Path -Path "C:\Program Files (x86)") -eq $true)
{
 $CSCriptLocation = "C:\Windows\Temp\cscript-admin-64.exe"
 $OSVersion = "64Bit"
}
else
{
 $CSCriptLocation = "C:\Windows\Temp\cscript-admin-32.exe"
 $OSVersion = "32Bit"
}

# Elevate CScript-Admin executionable file for Office 2010 scrub
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" /v $CSCriptLocation /t REG_SZ /d "RUNASADMIN" /f

# Uninstall Office 2010 using MS OffScrub10.vbs
$OfficeScrubArgs = " ProPlus /Bypass1 /NoCancel"
If ($OSVersion -eq "64Bit")
{
 $OfficeScrubCommand = "cmd /C C:\Windows\Temp\cscript-admin-64.exe \\YOURSERVER\YOURSHARE\YOURDIRECTORY\Office2010-Uninstall\OffScrub10.vbs $OfficeScrubArgs"
}
else
{
 $OfficeScrubCommand = "cmd /C C:\Windows\Temp\cscript-admin-32.exe \\YOURSERVER\YOURSHARE\YOURDIRECTORY\OffScrub10.vbs $OfficeScrubArgs"

}
Invoke-Expression $OfficeScrubCommand

# Outlook Registry Path
$OutlookReg = "\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles"

# Clean Outlook Profiles
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS
$UserSIDS = Get-ChildItem -Path HKU:\ | Split-Path -Leaf
foreach ($SID in $UserSIDS)
{
 $Profile = "HKU:\" + $SID + $OutlookReg
 $ProfileExists = Test-Path -Path $Profile
 if ($ProfileExists -eq $true)
 {
  Remove-Item -Path $Profile -Recurse -Force
 }
}
Remove-PSDrive -Name HKU

<# Un-comment this section to also clear OST & PST locations
$UserDirectories = Get-ChildItem -Path "C:\Users" | Where-Object { $_.PSIsContainer } | Select-Object FullName
$OutlookLocalAppData = "\AppData\Local\Microsoft\Outlook"
$OutlookLocalAppData = "\AppData\Roaming\Microsoft\Outlook"
foreach ($User in $UserDirectories.FullName)
{
 if ((Test-Path -Path (Join-Path $User $OutlookLocalAppData)) -eq $true)
 {
  Remove-Item -Path (Join-Path $User $OutlookLocalAppData) -Recurse -Force
 }
 if ((Test-Path -Path (Join-Path $User $OutlookRemoteAppData)) -eq $true)
 {
  Remove-Item -Path (Join-Path $User $OutlookRemoteAppData) -Recurse -Force
 }
}
#>