Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Script to disable users and export their files and email...

$
0
0

Hey Scripting Guys...

I have a script that I wrote for terminating users.  It disables the user, stamps the account with the time and date, removes them from all their AD Groups, exports their email to a .PST and compresses their user folders to a .zip file along with a few other things.  The script works.  With a hitch.  I get an error after the script runs that looks like this:

WARNING: The cmdlet extension agent with the index 5 has thrown an exception in
 OnComplete(). The exception is: System.InvalidOperationException: Operation is
 not valid due to the current state of the object.
   at
Microsoft.Exchange.Data.Storage.ExchangePrincipal.get_ServerFullyQualifiedDomai
nName()
   at Microsoft.Exchange.Data.Storage.MailboxSession.Initialize(MapiStore
linkedStore, LogonType logonType, ExchangePrincipal owner, DelegateLogonUser
delegateUser, Object identity, OpenMailboxSessionFlags flags, GenericIdentity
auxiliaryIdentity)
   at
Microsoft.Exchange.Data.Storage.MailboxSession.<>c__DisplayClass12.<CreateMailb
oxSession>b__10(MailboxSession mailboxSession)
   at
Microsoft.Exchange.Data.Storage.MailboxSession.InternalCreateMailboxSession(Log
onType logonType, ExchangePrincipal owner, CultureInfo cultureInfo, String
clientInfoString, IAccountingObject budget, Action`1 initializeMailboxSession,
InitializeMailboxSessionFailure initializeMailboxSessionFailure)
   at
Microsoft.Exchange.Data.Storage.MailboxSession.CreateMailboxSession(LogonType
logonType, ExchangePrincipal owner, DelegateLogonUser delegateUser, Object
identity, OpenMailboxSessionFlags flags, CultureInfo cultureInfo, String
clientInfoString, PropertyDefinition[] mailboxProperties, IList`1
foldersToInit, GenericIdentity auxiliaryIdentity, IAccountingObject budget)
   at
Microsoft.Exchange.Data.Storage.MailboxSession.ConfigurableOpen(ExchangePrincip
al mailbox, MailboxAccessInfo accessInfo, CultureInfo cultureInfo, String
clientInfoString, LogonType logonType, PropertyDefinition[] mailboxProperties,
InitializationFlags initFlags, IList`1 foldersToInit, IAccountingObject
budget)
   at
Microsoft.Exchange.Data.Storage.MailboxSession.OpenAsSystemService(ExchangePrin
cipal mailboxOwner, CultureInfo cultureInfo, String clientInfoString)
   at
Microsoft.Exchange.ProvisioningAgent.MailboxLoggerFactory.XsoMailer.Log(AdminLo
gMessageData data, LogMessageDelegate logMessage)
   at
Microsoft.Exchange.ProvisioningAgent.AdminLogProvisioningHandler.OnComplete(Boo
lean succeeded, Exception e)
   at Microsoft.Exchange.Provisioning.ProvisioningLayer.OnComplete(Task task,
Boolean succeeded, Exception exception)

 

My script looks like this:

#Created by Rob Smura 2/7/2013
#Updated 8/5/2013 to use 7-Zip instead of .zip
#Updated 3/5/2013 to add Disabled date to description, move the user to Retired Users OU and forward email of user to someone.
#This script must be run in an Exchange Management PowerShell or on a machine with the Exchange Management Tools installed.
#The script will prompt for username to be disabled, their firstname.lastname and a forward email to: username


add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
Import-Module ActiveDirectory
$UserName = $null
$UserFullName = $null
$ForwardMail = $null
$UserName = read-host -Prompt "Enter the username"
$UserFullName = read-host -Prompt "Enter FirstName.LastName"
$ForwardMail = Read-Host -Prompt "Enter the username to forward the user's mail to"
$ExportFilePath="\\KBackR\Former Users"
$FileServerPath="\\KleinDB\user"

#Creates folder to store Files and .PST in
$FormerUserStoragePath = "$ExportFilePath\$UserFullName"
if(!(Test-Path $FormerUserStoragePath))
	{
	[void](New-Item -path $ExportFilePath -name $UserFullName -type directory)
	}


#Remove User from all existing group memberships
# Retreive group membership of $Username
$SourceUser = Get-ADUser $UserName -Properties memberOf
# Enumerate direct group memberships
ForEach ($SourceDN In $SourceUser.memberOf)
{
	# Remove the target user from this group and don't bother asking for confirmation.
	Remove-ADGroupMember -Identity $SourceDN -Members $UserName -Confirm:$false
}

#Diable user
Set-ADUser $UserName -enabled $false

#Change Description of user to 'Disabled and today's date stamp'
$DateStamp = Get-Date -DisplayHint Date
Set-ADUser $UserName -Replace @{description="User Disabled: " + $DateStamp}

#Hide user from GlobalAddressLists
Get-Mailbox $UserName | Set-Mailbox -HiddenFromAddressListsEnabled $true

#Move user to Retired Users OU
Get-ADUser $UserName| Move-ADObject -TargetPath 'OU=Retired Users,DC=Kleinsteel,DC=com'


#Exports mailbox to .PST
$PSTFileName = "$ExportFilePath\$UserFullName\$UserFullName.pst"

If (Test-Path $PSTFileName)
	{
	$OldPSTFileName = "$PSTFileName" + ".old"
	If (Test-Path $OldPSTFileName)
		{
		Remove-Item -path $OldPSTFileName
		}
	Rename-Item -path ("$PSTFilename") -NewName ("$PSTFileName.old")
	}
#Forwards email to the $ForwardingAddress if it's not $null.
If ($ForwardMail -ne "'r")
{
	Set-Mailbox -Identity ("$UserName") -ForwardingAddress "$ForwardMail@kleinsteel.com"
}
else{}#Do Nothing

#Export mailbox to .PST
New-MailboxExportRequest -mailbox ("$UserName@kleinsteel.com") -filepath "$ExportFilePath\$UserFullName\$UserFullName.pst"

#Uses 7-Zip to compress the user's folders and place them in the same location as the mail archive.
try{
Set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"
if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe" )) { #Check if 7zip exist in the machine
throw ("$env:ProgramFiles\7-Zip\7z.exe needed.  Run the command 7z.exe a -mx9 -mmt=on $ExportFilePath\$UserFullName.7z $FileServerPath\UserFullName")
}
try{
Write-Host "Compressing using 7zip"
sz a -mx9 -mmt=on $ExportFilePath\$UserFullName\$UserFullName.7z $FileServerPath\$UserName
}
catch{
throw ("Error during the archive operation")
}
}
catch{
throw( $error[0])
}
Write-Host -ForegroundColor green "Folders successfully compressed"


#This line removes the completed mailbox export request.  If it fails, run just this Get-MailboxExportRequest line again.
Get-MailBoxExportRequest #Show the existing Export Requests
Get-MailboxExportRequest | where {$_.status -eq "Completed"} | Remove-MailBoxExportRequest #Remove the completed Export Requests if there are any
Remove-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
Remove-Module ActiveDirectory
$AnyKey = read-host -Prompt "Press any key to continue..." #Just a pause to keep the powershell window from closing so you can view msgs / errors.


I have looked all over and can't figure out what the error really means or how to get rid of it, especially since the script does what it is supposed to do...





Viewing all articles
Browse latest Browse all 15028

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>