Unable to import .CSV file into Get-MailBox command?

Hi All,

I've got the script below that takes the list of First Last name and then export the mailbox content as First.Last@domain.com.PST to the remote FileServer.

If there is already.PST with the same email name, then skip it.

This is the code:

$Server = 'PRODFS01-VM'
$ServerBackupUNCPath = "\\$Server\PST"
$InputCSVPath = 'C:\LOGS\Input.csv'
$ExportCSVPath = 'C:\LOGS\Output.csv'
$ExportExistsCSVPath = 'C:\LOGS\EmailExist.csv'

Import-PSSession ($Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://PRDEXC03-VM/Powershell/ -Authentication Kerberos)

$Users = Get-Content -Path $InputCSVPath
&{
foreach ($User in $Users) {
Write-Host "Processing.... $User"
Get-Mailbox $User.ToString() | Select WindowsEmailAddress
}
} | Export-Csv -Path $ExportCSVPath -NoTypeInformation

Import-Csv -Path $ExportCSVPath |
Get-MailBox |
% {
Write-Host "Processing .... $($_.Name) ..." -ForegroundColor Green

# Check if the file already exist or not
$FileResult = Test-Path -Path "$ServerBackupUNCPath\$($_.WindowsEmailAddress).PST" -PathType Leaf

if ( $FileResult -ne $True ) {
#If there is no exported .PST file on the destination folder, then begin the export mailbox command and log if there any error to the AliasName.LOG file:
New-MailboxExportRequest -Mailbox $_ -FilePath "$ServerBackupUNCPath\$($_.WindowsEmailAddress).PST" -BadItemLimit 50 -AcceptLargeDataLoss -WhatIf
# wait until error or processed:
while ( ($req = Get-MailboxExportRequest $_) | ? { $_.Status -match 'Queued|InProgress' } )
{ Start-Sleep 180 }
$req | Get-MailboxExportRequestStatistics -IncludeReport | Select -Expand Report | Out-File "C:\LOGS\$($_.WindowsEmailAddress).log"
} else {
Write-Output "The user $($_.WindowsEmailAddress).PST file is already existing"
#Append the list of already existing list of users C:\LOGS\Exist.csv
($_.Alias) | Out-File -FilePath $ExportExistsCSVPath -Append
}

# I assume, whatever line I put here will be executed regardless of any of the condition above is met or not
Write-Host "Removing Mailbox $($_.WindowsEmailAddress)" -ForegroundColor Red
Remove-Mailbox -Identity $_ -Confirm $false -WhatIf

}

This is the content of the Output.CSV:

"WindowsEmailAddress"
"Russel.Peters@domain.com"
"Amalia.Zebech@domain.com"
"Henry.Ho@domain.com"
"Bing.Fang@domain.com"
"Karina.Michaels@domain.com"


This is the error that stops me on the Get-Mailbox cmd let:

The operation couldn't be performed because object '"WindowsEmailAddress"' couldn't be found on 'PRODDC01-VM.domain.com'.
+ CategoryInfo : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : [Server=PRDEXC03-VM,RequestId=c061c8a3-72b6-469a-8109-726e1b015441,TimeStamp=21/08/2018 12:12:13 AM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] ED9B9A7,Microsoft.Exchange.Management.RecipientTasks.GetMailbox
+ PSComputerName : PRDEXC03-VM

The operation couldn't be performed because object '"Russel.Peters@domain.com"' couldn't be found on 'PRODDC01-VM.domain.com'.
+ CategoryInfo : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : [Server=PRDEXC03-VM,RequestId=c061c8a3-72b6-469a-8109-726e1b015441,TimeStamp=21/08/2018 12:12:13 AM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] FE47387B,Microsoft.Exchange.Management.RecipientTasks.GetMailbox
+ PSComputerName : PRDEXC03-VM

The operation couldn't be performed because object '"Amalia.Zebech@domain.com"' couldn't be found on 'PRODDC01-VM.domain.com'.
+ CategoryInfo : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : [Server=PRDEXC03-VM,RequestId=c061c8a3-72b6-469a-8109-726e1b015441,TimeStamp=21/08/2018 12:12:13 AM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] 3DFB1CD9,Microsoft.Exchange.Management.RecipientTasks.GetMailbox
+ PSComputerName : PRDEXC03-VM

.....

The operation couldn't be performed because object '"Karina.Michaels@domain.com"' couldn't be found on 'PRODDC01-VM.domain.com'.
+ CategoryInfo : NotSpecified: (:) [Get-Mailbox], ManagementObjectNotFoundException
+ FullyQualifiedErrorId : [Server=PRDEXC03-VM,RequestId=c061c8a3-72b6-469a-8109-726e1b015441,TimeStamp=21/08/2018 12:12:13 AM] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] 3DFB1CD9,Microsoft.Exchange.Management.RecipientTasks.GetMailbox
+ PSComputerName : PRDEXC03-VM

Thank you in advance for your help.

  • ,

    Hi.

    Can you try to modify this line?

    Get-Mailbox $User.ToString() | Select WindowsEmailAddress

    to

    Get-Mailbox $User.ToString() | Select WindowsEmailAddress -ExpandProperty WindowsEmailAddress

    And check if your code can replace the "" from the output so the Get-Mailbox looks for Karina.Michaels@domain.com instead of "Karina.Michaels@domain.com"


  • This is because you have syntax and logic issues in your script. You simply are not getting what you'd expect so it is important that you always build and test you code one step at a time to make sure you are getting what you are after.

    I have not PST in my labs, so I cannot test that but cleaning up you code and fixing what errors exits to actually get results, would look something like this. Of course I used account in my lab for this base test to prove it out, but obviously took those out in this post back.

        
        # Set needed variables. Use a unique prefix to allow for easy clean up
        # and to avoid variable persistence issues on subsequent runs
       

        $pnoServer = 'PRODFS01-VM'
        $pnoExchangeServer = 'ex01.contoso.com'
        $pnoServerBackupUNCPath = "\\$Server\PST"
        $pnoInputCSVPath = 'C:\Scripts\Input.csv'
        $pnoExportCSVPath = 'C:\Scripts\Output.csv'
        $pnyExportExistsCSVPath = 'C:\LOGS\EmailExist.csv'
        Get-Variable -Name 'pno*' | Format-Table -AutoSize

        # Results
        #
         Name                   Value               
        ----                   -----               
        pnoExchangeServer      cas01.contoso.com   
        pnoExportCSVPath       C:\Scripts\Output.csv
        pnoInputCSVPath        C:\Scripts\Input.csv
        pnoServer              PRODFS01-VM         
        pnoServerBackupUNCPath \\\PST
        #

        # Set params for implicit remote Exchange session
        $pnoParams = @{
            ConfigurationName = 'Microsoft.Exchange'
            ConnectionUri = "http://$pnoExchangeServer/Powershell/"
            Authentication = 'Kerberos'
        }
        Get-Variable -Name 'pno*' | Format-Table -AutoSize
       
        # Results
        #
        Name                   Value                                            
        ----                   -----                                            
        pnoExchangeServer      EX01.contoso.com                           
        pnoExportCSVPath       C:\Scripts\Output.csv                            
        pnoInputCSVPath        C:\Scripts\Input.csv                             
        pnoParams              {ConfigurationName, ConnectionUri, Authentication}
        pnoServer              PRODFS01-VM                                      
        pnoServerBackupUNCPath \\\PST  
        #

        # Instantiate a implicit Exchange remote session
        Import-PSSession -Session ($pnoSession = New-PSSession @pnoParams) -Prefix 'pno'

        # Results
        #
        WARNING: The names of some imported commands from the module 'tmp_samifhbh.vtq' include unapproved verbs that might make them less discoverable. To fi
        nd the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.

        ModuleType Version    Name                                ExportedCommands                                                                          
        ---------- -------    ----                                ----------------                                                                          
        Script     1.0        tmp_samifhbh.vtq                    {Add-pnoADPermission, Add-pnoAvailabilityAddressSpace, Add-pnoContentFilterPhrase, Add-p...
        #

        Get-PSSession | Format-Table -AutoSize

        # Results
        #

        Id Name     ComputerName     State  ConfigurationName  Availability
        -- ----     ------------     -----  -----------------  ------------
         2 Session2 ex01.contoso.com Opened Microsoft.Exchange    Available
        #

        Get-Command -Name '*-pno*' | Format-Table -AutoSize

        # Results
        #
        PS C:\Scripts> Get-Command -Name '*-pno*' | Format-Table -AutoSize

        CommandType Name                                                 ModuleName     
        ----------- ----                                                 ----------     
        ...
        Function    Get-pnoMailbox                                       tmp_3glm5c4q.vr4
        ...
        #

        # Import the CSV, using variable squezzing to show the imported records.
        ($pnoUsers = Import-Csv -Path $pnoInputCSVPath) | Format-Table -AutoSize

        # Results
        #

        WindowsEmailAddress      
        -------------------      
        Russel.Peters@domain.com 
        Amalia.Zebech@domain.com 
        Henry.Ho@domain.com      
        Bing.Fang@domain.com     
        Karina.Michaels@domain.com
        #

        # Process records to retrieve mailbox info
        foreach ($pnoUser in $pnoUsers)
        {
            "Processing.... $($pnoUser.WindowsEmailAddress)"
            Get-pnoMailbox -Identity $pnoUser.WindowsEmailAddress |
            Export-Csv -Path $pnoExportCSVPath -NoTypeInformation -Append
        }

        # Results
        #

        Processing.... Russel.Peters@domain.com 
        Processing.... Amalia.Zebech@domain.com 
        Processing.... Henry.Ho@domain.com      
        Processing.... Bing.Fang@domain.com     
        Processing.... Karina.Michaels@domain.com

        #

        Import-csv -Path $pnoExportCSVPath | Select SamAccountName,Name,Alias,WindowsEmailAddress | Format-Table -AutoSize

        # Results
        #
        SamAccountName   Name                Alias            WindowsEmailAddress    
        --------------   ----                -----            -------------------    
        Russel.Peters    Russel.Peters       Russel.Peters    Russel.Peters@domain.com 
        Amalia.Zebech    Amalia.Zebech       Amalia.Zebech    Amalia.Zebech@domain.com 
        Henry.Ho         Henry.Ho            Henry.Ho         Henry.Ho@domain.com      
        Bing.Fang        Bing.Fang           Bing.Fang        Bing.Fang@domain.com     
        Karina.Michaels  Karina.Michaels     Karina.Michaels  Karina.Michaels@domain.com
        #

        $pnoUserMailBoxes = Import-Csv -Path $pnoExportCSVPath
        ForEach ($pnoUserMailBox in $pnoUserMailBoxes)
        {
            Write-Host "Processing .... $($pnoUserMailBox.Name) ..." -ForegroundColor Green

            Get-MailBox -Identity $pnoUserMailBox.SamAccountName

            # Check if the file already exist or not
            $pnoFileResult = Test-Path -Path "$pnoServerBackupUNCPath\$($pnoUserMailBox.WindowsEmailAddress).PST" -PathType Leaf

            if ( $pnoFileResult -ne $True )
            {
                #
                # If there is no exported .PST file on the destination folder, then begin
                # the export mailbox command and log if there any error to the AliasName.LOG file:
                #

                $pnoParams = @{
                    Mailbox = $_
                    FilePath = "$pnoServerBackupUNCPath\$($pnoUserMailBox.WindowsEmailAddress).PST"
                    BadItemLimit = 50
                    AcceptLargeDataLoss = $true
                }

                New-MailboxExportRequest @pnoParams -WhatIf
           
                # wait until error or processed:
                while ( ($pnoReq = Get-MailboxExportRequest $pnoUserMailBox.WindowsEmailAddress) |
                Where-Object { $_.Status -match 'Queued|InProgress' } )
                { Start-Sleep 180 }

                $pnoReq | Get-MailboxExportRequestStatistics -IncludeReport |
                Select -Expand Report |
                Out-File "C:\LOGS\$($pnoUserMailBox.WindowsEmailAddress.WindowsEmailAddress).log"
            }
            else
            {
                "The user $($pnoUserMailBox.WindowsEmailAddress.WindowsEmailAddress). PST file is already existing"

                #Append the list of already existing list of users C:\LOGS\Exist.csv
                ($pnoUserMailBox.Alias) | Out-File -FilePath $pnoExportExistsCSVPath -Append
            }

            # I assume, whatever line I put here will be executed regardless of any of the condition above is met or not
            Write-Host "Removing Mailbox $($pnoUserMailBox.WindowsEmailAddress.WindowsEmailAddress)" -ForegroundColor Red
            Remove-Mailbox -Identity $pnoUserMailBox.WindowsEmailAddress -Confirm $false -WhatIf
        }

        # Clean-up run environment - tp prevent varialbe and other persistance for subsequent runs
        Get-PSSession | Remove-PSSession
        $null = [System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$Shell)
        [System.GC]::Collect()
        [GC]::Collect()
        [GC]::WaitForPendingFinalizers()
        Get-Variable -Name '*pno*' | Remove-Variable -Force