SlideShare a Scribd company logo
1 of 3
<#Import in modules, if statement for PSSnapin so that it doesn't throw
an error if it is already loaded.#>
Import-Module ActiveDirectory
if ( (Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Admin -
ErrorAction SilentlyContinue) -eq $null )
{
add-pssnapin Microsoft.Exchange.Management.PowerShell.Admin
}
<#Clear variables so they are not retaining any old values#>
Get-Variable -Exclude PWD,*Preference | Remove-Variable -EA 0
<#Variables needed to complete script. $testIteration shows the number of
times nested for loop happens, $exUserCorpMatch=@() is an empty array
that will have objects added to it
when linked mailboxes on Exchange are compared to disabled corp accounts,
the $adminUser and $adPW are the login credentials so that anyone can
enter admin login credentials to run script#>
$errorLogPath = "c:scriptslogsexchangeADerror.txt"
$testIteration=0
$exUserCorpMatch=@()
$adminUser = whoami
$exceptionUsers=@()
$exceptionArray=@()
<#Create an Array from Get-mailbox cmdlet that has the value
"LinkedMailbox" tying it to a Corporate account, .count value used to
check results against expected#>
$mailboxes = Get-Mailbox -resultSize unlimited -RecipientTypeDetails
LinkedMailbox
$mailboxes.count
<#Create an array of objects from Corp server of user only dissabled
accounts, .count value used to check results against expected#>
$corpAccDis = Search-ADAccount -ResultSetSize $null -Server
SanitizedServerName -AccountDisabled -UsersOnly
$corpAccDis.count
<#Read in a list of users whose mailboxes shouldn't be removed#>
while ($var -ne "q"){
$var = Read-Host "Enter user exception linked mailbox name, or press
q to quit entering names:"
if ($var -ne "q"){
$exceptionUsers += $var
}
}
$exceptionUsers.count
<#Create an Array with the usernames that were supplied by the Read-Host
Cmdlet#>
foreach ($name in $exceptionUsers){
$exceptionArray += Get-Mailbox -Identity $name
}
$exceptionArray
<#Compare the two arrays on the value of name from the "Linked Master
Account" and the Corp server "Sam Account Name" and insert the matching
objects into an Array#>
For ($a=0 ; $a -le $mailboxes.count -1 ; $a++){
For ($b=0 ; $b -le $corpAccDis.count -1 ; $b++){
$testIteration++
if
($mailboxes[$a].LinkedMasterAccount.Split("")[-1] -eq
$corpAccDis[$b].SamAccountName){
$exUserCorpMatch += $mailboxes[$a]
break
}
}
}
$testIteration #Test value checking nember of times the loop took place
$exUserCorpMatch.count
<#For loop to take exception users mailboxes out of the script#>
For ($d=0;$d -lt $exceptionArray.Count; $d++){
$exUserCorpMatch = $exUserCorpMatch| ? {$_.alias -ne
$exceptionArray[$d].alias}
}
$exUserCorpMatch.count
$exUserCorpMatch | sort
<#Taking the newly created array from the comparison and running the bulk
of decisions, gives full access rights to the before entered admin
account, then exports the mailbox to a PST
file on the network share, and produces a txt file of the users
properties, attributes, etc.. Then removes-mailbox, this is cmdlet is
currently commented out until testing is done and
confirmed removal is ready to take place. #>
for ($c = 0 ; $c -le $exUserCorpMatch.count -1; $c++){
$fileCreationTime = Get-Date -UFormat "%Y%m%d%H%M%S"
$displayName = $exUserCorpMatch[$c].DisplayName
$pstFolderPath = Join-Path "SanitizedServerNameexchangePST"
$fileCreationTime$displayName.PST
$txtFolderPath = Join-Path "SanitizedServerNameexchangePST"
$fileCreationTime$displayName.txt
try {
$everythingIsOk = $true
Add-MailboxPermission -Identity $exUserCorpMatch[$c] -User
$adminUser -AccessRights FullAccess -ErrorAction Stop -Verbose -
Confirm:$false
} catch {
$everythingIsOk = $false
Write-Warning "Permission add problem, logging error to
$errorLogPath!"
Write-Warning $error[0]
$error[0] | Out-File $errorLogPath -Append
}
if ($everythingIsOk){
try{
Export-Mailbox -Identity $exUserCorpMatch[$c] -PSTFolderPath
$pstFolderPath -ErrorAction Stop -Verbose -Confirm:$false
}catch{
$everythingIsOk = $false
Write-Warning "Export problem!"
Write-Warning $error[0]
$error[0] | Out-File $errorLogPath -Append
}
}
if ($everythingIsOk){
try {
Get-Mailbox -Identity $exUserCorpMatch[$c] | FL | Out-File
$txtFolderPath -ErrorAction Stop -Verbose -Confirm:$false
} catch {
$everythingIsOk = $false
Write-Warning "Problem writing to txt"
Write-Warning $error[0]
$error[0] | Out-File $errorLogPath -Append
}
}
if ($everythingIsOk){
try{
Write-Verbose "!!!!!!!!!!!!!!!!!!"
Remove-Mailbox -Identity $exUserCorpMatch[$c] -Permanent $true -
ErrorAction Stop -Verbose -Confirm:$false
} catch {
Write-Warning $error[0]
$error[0] | Out-File $errorLogPath -Append
}
}
}

More Related Content

What's hot

Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Roel Hartman
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
MongoDB
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
Powershell function
Powershell functionPowershell function
Powershell function
LearningTech
 

What's hot (19)

Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React Alicante
 
Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.Migrating from Flux to Redux. Why and how.
Migrating from Flux to Redux. Why and how.
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Source Code for Dpilot
Source Code for Dpilot Source Code for Dpilot
Source Code for Dpilot
 
Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots
 
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...Developing A Real World Logistic Application With Oracle Application - UKOUG ...
Developing A Real World Logistic Application With Oracle Application - UKOUG ...
 
Introduction to CQRS and Event Sourcing
Introduction to CQRS and Event SourcingIntroduction to CQRS and Event Sourcing
Introduction to CQRS and Event Sourcing
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
Cakephp2study tips集
Cakephp2study tips集Cakephp2study tips集
Cakephp2study tips集
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
 
Event sourcing w PHP (by Piotr Kacała)
Event sourcing w PHP (by Piotr Kacała)Event sourcing w PHP (by Piotr Kacała)
Event sourcing w PHP (by Piotr Kacała)
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
 
Java day9n
Java day9nJava day9n
Java day9n
 
Building Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at StripeBuilding Real Time Systems on MongoDB Using the Oplog at Stripe
Building Real Time Systems on MongoDB Using the Oplog at Stripe
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Powershell function
Powershell functionPowershell function
Powershell function
 

Viewers also liked

Zacatecas
ZacatecasZacatecas
Zacatecas
indesol
 
Children in need donation letter 2012
Children in need donation letter 2012Children in need donation letter 2012
Children in need donation letter 2012
CJH47
 
La historia de las cosas
La historia de las cosasLa historia de las cosas
La historia de las cosas
beatrizzzzzz
 
Sampurna Tanavmukti Aani Samasyapurti (Total Stress Management In Marathi) Dr...
Sampurna Tanavmukti Aani Samasyapurti (Total Stress Management In Marathi) Dr...Sampurna Tanavmukti Aani Samasyapurti (Total Stress Management In Marathi) Dr...
Sampurna Tanavmukti Aani Samasyapurti (Total Stress Management In Marathi) Dr...
Ameet Fadia
 

Viewers also liked (19)

Messed up kids
Messed up kidsMessed up kids
Messed up kids
 
Mission In The West
Mission In The WestMission In The West
Mission In The West
 
Undang undang kesehatan jiwa
Undang undang kesehatan jiwaUndang undang kesehatan jiwa
Undang undang kesehatan jiwa
 
Zacatecas
ZacatecasZacatecas
Zacatecas
 
Children in need donation letter 2012
Children in need donation letter 2012Children in need donation letter 2012
Children in need donation letter 2012
 
INSTALLING JAVA
INSTALLING JAVAINSTALLING JAVA
INSTALLING JAVA
 
Lotus petals
Lotus petalsLotus petals
Lotus petals
 
La historia de las cosas
La historia de las cosasLa historia de las cosas
La historia de las cosas
 
PSYCHOLOGY OF TESTING
PSYCHOLOGY OF TESTINGPSYCHOLOGY OF TESTING
PSYCHOLOGY OF TESTING
 
Sampurna Tanavmukti Aani Samasyapurti (Total Stress Management In Marathi) Dr...
Sampurna Tanavmukti Aani Samasyapurti (Total Stress Management In Marathi) Dr...Sampurna Tanavmukti Aani Samasyapurti (Total Stress Management In Marathi) Dr...
Sampurna Tanavmukti Aani Samasyapurti (Total Stress Management In Marathi) Dr...
 
L'immobilier 100% entre particuliers Edition Janvier/Février 2016 AI102
L'immobilier 100% entre particuliers Edition Janvier/Février 2016 AI102L'immobilier 100% entre particuliers Edition Janvier/Février 2016 AI102
L'immobilier 100% entre particuliers Edition Janvier/Février 2016 AI102
 
RSM Astute - SSA LLP Group: Learning and Development Culture
RSM Astute - SSA LLP Group: Learning and Development CultureRSM Astute - SSA LLP Group: Learning and Development Culture
RSM Astute - SSA LLP Group: Learning and Development Culture
 
Portfolio_DirujiDugarte2016_opt
Portfolio_DirujiDugarte2016_optPortfolio_DirujiDugarte2016_opt
Portfolio_DirujiDugarte2016_opt
 
ประเด็นคำถาม เรื่องพรบ.ข้อมูลข่าวสาร
ประเด็นคำถาม เรื่องพรบ.ข้อมูลข่าวสารประเด็นคำถาม เรื่องพรบ.ข้อมูลข่าวสาร
ประเด็นคำถาม เรื่องพรบ.ข้อมูลข่าวสาร
 
The Data Opportunity - Rock your data with Segment.com
The Data Opportunity - Rock your data with Segment.comThe Data Opportunity - Rock your data with Segment.com
The Data Opportunity - Rock your data with Segment.com
 
subhadip chatterjee
subhadip chatterjeesubhadip chatterjee
subhadip chatterjee
 
TINCIÓN GRAM
TINCIÓN GRAMTINCIÓN GRAM
TINCIÓN GRAM
 
Playboy Club - Playboy Parties London
Playboy Club - Playboy Parties LondonPlayboy Club - Playboy Parties London
Playboy Club - Playboy Parties London
 
RSME_MHaji
RSME_MHajiRSME_MHaji
RSME_MHaji
 

Similar to exportDisabledUsersRemoveMailbox

PowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdfPowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdf
outcast96
 

Similar to exportDisabledUsersRemoveMailbox (20)

MassChangeCORPEmail
MassChangeCORPEmailMassChangeCORPEmail
MassChangeCORPEmail
 
getSIDUsers
getSIDUsersgetSIDUsers
getSIDUsers
 
MassMigrateUsersOU
MassMigrateUsersOUMassMigrateUsersOU
MassMigrateUsersOU
 
Testowanie JavaScript
Testowanie JavaScriptTestowanie JavaScript
Testowanie JavaScript
 
Rest with-spray
Rest with-sprayRest with-spray
Rest with-spray
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
termUserGroups
termUserGroupstermUserGroups
termUserGroups
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
An Introduction to Windows PowerShell
An Introduction to Windows PowerShellAn Introduction to Windows PowerShell
An Introduction to Windows PowerShell
 
PowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdfPowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdf
 
Speed Things Up with Transients
Speed Things Up with TransientsSpeed Things Up with Transients
Speed Things Up with Transients
 
Power shell voor developers
Power shell voor developersPower shell voor developers
Power shell voor developers
 
TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShell
 
Ruby on Rails testing with Rspec
Ruby on Rails testing with RspecRuby on Rails testing with Rspec
Ruby on Rails testing with Rspec
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 

exportDisabledUsersRemoveMailbox

  • 1. <#Import in modules, if statement for PSSnapin so that it doesn't throw an error if it is already loaded.#> Import-Module ActiveDirectory if ( (Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Admin - ErrorAction SilentlyContinue) -eq $null ) { add-pssnapin Microsoft.Exchange.Management.PowerShell.Admin } <#Clear variables so they are not retaining any old values#> Get-Variable -Exclude PWD,*Preference | Remove-Variable -EA 0 <#Variables needed to complete script. $testIteration shows the number of times nested for loop happens, $exUserCorpMatch=@() is an empty array that will have objects added to it when linked mailboxes on Exchange are compared to disabled corp accounts, the $adminUser and $adPW are the login credentials so that anyone can enter admin login credentials to run script#> $errorLogPath = "c:scriptslogsexchangeADerror.txt" $testIteration=0 $exUserCorpMatch=@() $adminUser = whoami $exceptionUsers=@() $exceptionArray=@() <#Create an Array from Get-mailbox cmdlet that has the value "LinkedMailbox" tying it to a Corporate account, .count value used to check results against expected#> $mailboxes = Get-Mailbox -resultSize unlimited -RecipientTypeDetails LinkedMailbox $mailboxes.count <#Create an array of objects from Corp server of user only dissabled accounts, .count value used to check results against expected#> $corpAccDis = Search-ADAccount -ResultSetSize $null -Server SanitizedServerName -AccountDisabled -UsersOnly $corpAccDis.count <#Read in a list of users whose mailboxes shouldn't be removed#> while ($var -ne "q"){ $var = Read-Host "Enter user exception linked mailbox name, or press q to quit entering names:" if ($var -ne "q"){ $exceptionUsers += $var } } $exceptionUsers.count <#Create an Array with the usernames that were supplied by the Read-Host Cmdlet#> foreach ($name in $exceptionUsers){ $exceptionArray += Get-Mailbox -Identity $name } $exceptionArray
  • 2. <#Compare the two arrays on the value of name from the "Linked Master Account" and the Corp server "Sam Account Name" and insert the matching objects into an Array#> For ($a=0 ; $a -le $mailboxes.count -1 ; $a++){ For ($b=0 ; $b -le $corpAccDis.count -1 ; $b++){ $testIteration++ if ($mailboxes[$a].LinkedMasterAccount.Split("")[-1] -eq $corpAccDis[$b].SamAccountName){ $exUserCorpMatch += $mailboxes[$a] break } } } $testIteration #Test value checking nember of times the loop took place $exUserCorpMatch.count <#For loop to take exception users mailboxes out of the script#> For ($d=0;$d -lt $exceptionArray.Count; $d++){ $exUserCorpMatch = $exUserCorpMatch| ? {$_.alias -ne $exceptionArray[$d].alias} } $exUserCorpMatch.count $exUserCorpMatch | sort <#Taking the newly created array from the comparison and running the bulk of decisions, gives full access rights to the before entered admin account, then exports the mailbox to a PST file on the network share, and produces a txt file of the users properties, attributes, etc.. Then removes-mailbox, this is cmdlet is currently commented out until testing is done and confirmed removal is ready to take place. #> for ($c = 0 ; $c -le $exUserCorpMatch.count -1; $c++){ $fileCreationTime = Get-Date -UFormat "%Y%m%d%H%M%S" $displayName = $exUserCorpMatch[$c].DisplayName $pstFolderPath = Join-Path "SanitizedServerNameexchangePST" $fileCreationTime$displayName.PST $txtFolderPath = Join-Path "SanitizedServerNameexchangePST" $fileCreationTime$displayName.txt try { $everythingIsOk = $true Add-MailboxPermission -Identity $exUserCorpMatch[$c] -User $adminUser -AccessRights FullAccess -ErrorAction Stop -Verbose - Confirm:$false } catch { $everythingIsOk = $false Write-Warning "Permission add problem, logging error to $errorLogPath!" Write-Warning $error[0] $error[0] | Out-File $errorLogPath -Append
  • 3. } if ($everythingIsOk){ try{ Export-Mailbox -Identity $exUserCorpMatch[$c] -PSTFolderPath $pstFolderPath -ErrorAction Stop -Verbose -Confirm:$false }catch{ $everythingIsOk = $false Write-Warning "Export problem!" Write-Warning $error[0] $error[0] | Out-File $errorLogPath -Append } } if ($everythingIsOk){ try { Get-Mailbox -Identity $exUserCorpMatch[$c] | FL | Out-File $txtFolderPath -ErrorAction Stop -Verbose -Confirm:$false } catch { $everythingIsOk = $false Write-Warning "Problem writing to txt" Write-Warning $error[0] $error[0] | Out-File $errorLogPath -Append } } if ($everythingIsOk){ try{ Write-Verbose "!!!!!!!!!!!!!!!!!!" Remove-Mailbox -Identity $exUserCorpMatch[$c] -Permanent $true - ErrorAction Stop -Verbose -Confirm:$false } catch { Write-Warning $error[0] $error[0] | Out-File $errorLogPath -Append } } }