Exchange mailboxes, corporate AD, forest trust, arrays, Can you look this over?

This is my first script, it took a while to figure some things out, but it is working. I wanted to know if it is overkill, or if there is something that sticks out that would be an easier way of accomplishing something with this script.
Background info:
Company was bought out, forest trust set up between corp network and ours (years ago). So what we wanted was to compare exchange mailboxes with linked mailboxes array, to be compared to corporate AD array with user accounts that are disabled. a list is created
in another script which shows linked mailboxes and disabled corp AD accounts, helpdesk looks these through to make sure there are no exceptions. Exceptions are entered into PS cmdline, those are pulled out of the array. Then the left objects in the array are
PST backed up to network share, and then mailboxes removed. Admin trust across corp allows Exchange admin to search through Corp AD through search-AdAccount cmdlet. The script is run from a VM with exchange server tools installed and running 32-bit os of Windows
7 and 32-bit Office (Because that's how great... Exchange 2007 is for exporting mailboxes to PST). 
Not sure of this, though it works: 
<#Clear variables so they are not retaining any old values#>
Get-Variable -Exclude PWD,*Preference | Remove-Variable -EA 0
Wanted to clear variables before running script, data was being held over each run before adding this in
Here is the code "xxxxx" used in lieu of server names:
<#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:\scripts\logs\exchangeADerror.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 xxxxx -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 "\\xxxxx\exchangePST\" $fileCreationTime$displayName.PST
    $txtFolderPath = Join-Path "\\xxxxx\exchangePST\" $fileCreationTime$displayName.txt
    try {
        $everythingIsOk = $true
        Add-MailboxPermission -Identity $exUserCorpMatch[$c] -User $adminUser -AccessRights FullAccess -ErrorAction Stop -Verbose
    } 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
        }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
        } 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#>
        } catch {
         Write-Warning $error[0]
         $error[0] | Out-File $errorLogPath -Append

Half of you code appears to be doing nothing.
This does nothing:
if ($everythingIsOk){
        try{
        Write-Verbose "!!!!!!!!!!!!!!!!!!"
        <#Remove-Mailbox -Identity $exUserCorpMatch[$c] -Permanent $true -ErrorAction Stop -Verbose#>
        } catch {
         Write-Warning $error[0]
         $error[0] | Out-File $errorLogPath -Append
The way we do a limiting Try/Catch is to just use a single "try/catch".
$fileCreationTime = Get-Date -UFormat "%Y%m%d%H%M%S"
for ($c = 0 ; $c -lt $exUserCorpMatch.count; $c++){
$displayName = $exUserCorpMatch[$c].DisplayName
$pstFolderPath = Join-Path "\\xxxxx\exchangePST\" $fileCreationTime$displayName.PST
$txtFolderPath = Join-Path "\\xxxxx\exchangePST\" $fileCreationTime$displayName.txt
try {
Add-MailboxPermission -Identity $exUserCorpMatch[$c] -User $adminUser -AccessRights FullAccess -ErrorAction Stop -Verbose
Get-Mailbox -Identity $exUserCorpMatch[$c] | FL | Out-File $txtFolderPath -ErrorAction Stop -Verbose
<#Remove-Mailbox -Identity $exUserCorpMatch[$c] -Permanent $true -ErrorAction Stop -Verbose#>
}catch
Write-Warning $error[0]
$error[0] | Out-File $errorLogPath -Append
The following does the same thing your code did.  It executes but aborts further execution on an exception.
¯\_(ツ)_/¯

Similar Messages

  • Can you do this with ODP?

    I've got a question...
    I want to call a function with a mixture of bind parms and non-bind parms and return a refcursor. For instance,
    How would I call the following function with ODP: (BTW, I haven't compiled this so dont worry about the syntax. What I'm trying to accomplish is one round trip from the app server to the database that will return a query that is limited to the keys passed in as bind parms. Notice the join to the results table to restrict my production query to just those bind array values that are passed in after I insert them into my results table (index-organized table)). I get an error "SPECIFIED CAST IS NOT VALID" when I try to call this function with a mixture of bind parms (arrays) and non-bind parms. Can you do this? I do not see anything in the pdf file on the ODP documentation that says you cannot. but I'm thinking because you set the command.ArrayBindCount property to the number of things in your array, that this applies to ALL of the parms? Is that true? Any workarounds?
    Thanx
    Frank
    CREATE OR REPLACE PACKAGE mypkg IS
    TYPE RefCursor IS REF CURSOR;
    FUNCTION myExport(keyid_in IN VARCHAR2
    ,where_clause_in IN VARCHAR2
    ,sessionid_in IN VARCHAR2
    ,key_nbr_in IN NUMBER
    ,key_flag_in IN CHAR
    ,key2_in IN NUMBER
    ,key2_flag_in IN CHAR) RETURN RefCursor;
    END mypkg;
    SHOW ERRORS;
    CREATE OR REPLACE PACKAGE BODY mypkg IS
    FUNCTION myExport(keyid_in IN VARCHAR2
    ,where_clause_in IN VARCHAR2
    ,sessionid_in IN VARCHAR2
    ,key_nbr_in IN NUMBER
    ,key_flag_in IN CHAR
    ,key2_nbr_in IN NUMBER
    ,key2_flag_in IN CHAR) RETURN RefCursor IS
         myCur RefCursor;
    BEGIN
    -- This is not a bind parm, but one string value, not an array!
         DELETE FROM session_results WHERE sessionid = keyid_in;
    -- These are bind parms that will insert N records into my results table
    INSERT INTO results VALUES(sessionid_in
    ,key_nbr_in
    ,key_flag_in
    ,key2_nbr_in
    ,key2_flag_in);
         COMMIT;
         OPEN myCur FOR
    SELECT table1.key_nbr
    ,table1.key_flag
    ,table2.key2_nbr
    ,table2.key2_flag
    FROM table1
    ,results
    ,table2
    WHERE results.sessionid = keyid_in
    AND table1.key_nbr = sresl.key_nbr
    AND table1.key_flag = sresl.key_flag
    AND table1.key_nbr = table2.key_nbr
    AND table1.key_flag = table2.key_flag
    and table2.key_nbr = results.key2_nbr
    and table2.key_flag = results.key2_flag;
         RETURN(myCur);
    END myExport;
    END mypkg;
    SHOW ERRORS;

    Please correct me if my understanding is not correct but I believe your questions is whether one parameter can be an array bind while another is a non-array bind in a single stored procedure execution. If that is your question, the answer is no. All parameters must be either bound as an array or not bound as an array. There cannot be a mix.

  • Regarding receiving texts as emails:  Can you apply this setting to one individual? I want to continue to receive texts from everyone else except one person!

    Regarding receiving texts as emails:  Can you apply this setting to one individual? I want to continue to receive texts from everyone else except one person!

    Don't want to block the person, just have all his texts going directly to my email so that I can maintain a continuous record of his text contacts (rather than remain in text form).
    It appears that I must select an option that makes ALL texts go to email, which I'd prefer not doing.

  • I have no audio what so ever i have seen in one of the tables where it was deleted how can you fix this i tried everything i know

    == Issue
    ==
    I have another kind of problem with Firefox
    == Description
    ==
    i have been trying to get the audio to play for 3 days now i did see where it had been deleted this is a used comp i haven't had it long can you fix this i'm at my wits end
    == Firefox version
    ==
    3.6.3
    == Operating system
    ==
    Windows NT 5.0
    == User Agent
    ==
    Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3
    == Plugins installed
    ==
    *-Default Plug-in
    *Adobe Acrobat Plug-In Version 5.10 for Netscape
    *Java(TM) Platform SE binary
    *Next Generation Java Plug-in 1.6.0_20 for Mozilla browsers
    *Network Object Plugin
    *Windows Multimedia Services DRM Store Plug-In
    *Npdsplay dll

    Hello Virginia.
    You may be having a problem with some extension or plugin that is hindering your Firefox's normal behavior. Have you tried disabling all add-ons (just to check), to see if Firefox goes back to normal?

  • I have Photoshop CS4,on how many computers can you install this program ?

    Hello,
    I got Photoshop CS4. On how many computers can you install this program ?
    Sonste

    The license and activation rights are for a single user on two computers that are not used simultaneously—such as your desktop machine and your laptop.

  • Is there anyone there? I hope there is someone who can you understand this problem and have the common sense to respond?  I open gmail. I want to save an email to one of my folders. I position my cursor over the appropriate Folder icon or by choice, to th

    Is there anyone there? I hope there is someone who can you understand this problem and have the common sense to respond?
    I open gmail. I want to save an email to one of my folders.
    I position my cursor over the appropriate Folder icon or by choice, to the Trash.
    The friendly finger pointing cursor icon changes to an arrow icon.
    The hand icon allows me flawless access to opening and/or moving emails.
    The arrow, however does not open the link.
    On the Google menu bar the cursor hand with finger opens the links to Everett (my name), Search, Images, Maps and Play.
    When I attempt to open the remaining links in the menu bar (YouTube, News, Gmail, Drive, Calendar and More) the arrow icon replaces the hand. The arrow icon does not work. It will not activate these links.  Nor does it open email messages in the Inbox.
    Usually I reset, even reboot Safire and sometimes the problem goes away, then reappears.
    Can you imagine if this condition should it happen to a tech savvy Google Support person? Perhaps one can share and make my problem go away.
    I am considering dropping Google as my mail source. Unfortunate!
    Everett Halvorsen
    [email protected]
    718.490.3824

    I have uninstalled my Access Connection, but this problem seems to persist. IBM technician have changed the wireless card of my T60, the first few days after it was changed was very fine, no problem at all. About a week later, the problem occured again, and it happened quite frequently after that occurence. Now i really have no idea what is the cause and how to solve it. Will be greatful if there is anyone that can help me.

  • I have a lenovo S410 Touch laptop -with windows 8.1 -Itunes 11.1.1 ,i am trying to connect my iphone 4s but does not connect , it shows that it wants to connect , how can you connect this?

    I have a lenovo S410 Touch laptop -with windows 8.1 -Itunes 11.1.1 ,i am trying to connect my iphone 4s by USB cable but does not connect , it shows that it wants to connect , how can you connect this?

    http://support.apple.com/kb/ts1538

  • Hello I Download Adobe Photoshop CC 2014 Last Night i INSTALLED it But it Crashes in 30-40 Sec After i Launch the Product Without Any Error Message I Need Help Can You Resolve This Problem i Tried Creative Cloud Sign Out Nd Sign iN But iT DidnT ReSolve My

    Hello I Download Adobe Photoshop CC 2014 Last Night
     i INSTALLED it But it Crashes in 30-40 Sec After i Launch the Product Without Any Error Message
    I Need Help Can You Resolve This Problem

    Lotfi are you receiving any error messages during the installation?  I would recommend reviewing your installation logs for errors.  Please see Troubleshoot install issues with log files | CC - http://helpx.adobe.com/creative-cloud/kb/troubleshoot-install-logs-cc.html for information on how to locate and interpret your installation log files.  You are welcome to post any specific errors you discover to this discussion.

  • In v.4 fonts look blurry. Can you solve this shortcoming ?

    Fonts look blurry in the overall menu in this new version of browser (v.4). I tried all the options that you specified with the ClearType an so on... It seems that the problem is not from Windows 7 because the old version looks ok. Can you solve this shortcoming ?
    Until you resolve it I'll stay with the previous version (3.6.16) which it looks really good.

    Yea, when I actually install my applications and launch them from GNOME Shell's menu or launcher the fonts look as blurry as they do when I launch them from Anjuta. Other applications look fine and with the workarounds I described above, my own applications display nicely too when launched from either GNOME Shell or Anjuta.

  • I ordered Adobe XI pro last year and need to reinstall it.  I cannot find my serial number. I downloaded the software online.  Can you look up my order. I ordered it last year around this time.

    I ordered Adobe XI pro last year and need to reinstall it.  I cannot find my serial number. I downloaded the software online.  Can you look up my order. I ordered it last year around this time.@

    Once you get your S/N and download the software, back them up to a CD or backup HD. Not doing that is like purchasing a CD, installing software, and tossing the CD in the trash.

  • How can you search this forum without searching all the other forums

    how can you search this forum without searching all the other forums at the same time which is a big fat waste of time.

    Follow this tip to create a bookmark to a search page that searches only the forum you want or...
    Browse with Firefox and enable this Greasemonkey script, which forces all searches from a sub-forum to be local.

  • TS4006 can you look up your iphone 5 with out having set up your account in icloud?

    can you look up your iphone5 without having to set up your icloud? and disconnecting your phone after it got stolen?

    If you mean can you locate it without having set up iCloud, the answer is no.  You have to have set up iCloud and enabled Find My iPhone on your phone before it was stolen in order to locate it.

  • Can you convert this file into good searchable pdf file: Medical Terminology- A Short Course.azw4

    Can you convert this file into good searchable pdf file: Medical Terminology- A Short Course.azw4

    I don't think that Adobe offers any software to convert .azw4 files.  Search Google for alternate converters.

  • Can you look up the content of text messages that have been deleted

    Can you look up the content of previously deleted text messages?

    In the messages search bar, or the search bar of the iPhone, type in keywords from deleted messages.

  • HT204406 what if i do not want artwork for any song?  they take too long to upload and I personally don't care to retain or see the "artwork".  Can you diable this in itunes match?

    what if i do not want artwork for any song?  they take too long to upload and I personally don't care to retain or see the "artwork".  Can you diable this in itunes match?

    Agreed. I hope they allow this some time soon or iTunes Match will remain a big disappointment for me.

Maybe you are looking for