PowerShell to check file exist in the destination folder before exporting the Exchange email as .PST?

Ask your Windows PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
User avatar
ITEngineer
Posts: 89
Joined: Wed Oct 12, 2011 10:52 am

PowerShell to check file exist in the destination folder before exporting the Exchange email as .PST?

Post by ITEngineer » Sun Aug 19, 2018 11:30 pm

Hi People,

I need some assistance in fixing the below PowerShell script that can do the export First.LastName@domain.com.PST from the .CSV input file:

Code: Select all

Johny Hargreaves
Linda Marino
Henry Hosain
Vicki Cunard
Amalia Stokes
...
Check if the exported First.LastName@domain.com.PST is already existing on the destination fileserver \\PRODFS01-VM\PST\
if it exists then skip it and append the list First.LastName@domain.com.PST to a text file.
If not exist, then do the Export to PST as \\PRODFS01-VM\PST\First.LastName@domain.com.PST

Code: Select all

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

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

Get-Content -Path $InputCSVPath |
  Get-MailBox | 
  % {
    Write-Host "Processing .... $($_.Name) ..." -ForegroundColor Green
	
	# Check if the file already exist or not
	$FileResult = Get-WmiObject CIM_DataFile -ComputerName $Server -filter "path='$ServerBackupUNCPath'" | ? {$_.name -match "$($_.Alias).PST" }
	
	if ( $FileResult -eq $null ) {
		#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$($_.Alias).PST" -baditemlimit 50 -acceptlargedataloss 
	    # 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\$($_.Alias).log"
	} else {
		Write-Output "The user $($_.Alias).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
	Remove-Mailbox -Identity $_ -Confirm $false -WhatIf
  }
The line to do the comparison and appending the name of the already existing files is not working, hence I need some help to fix it.

Any help would be greatly appreciated very muchly.

Thanks,

Thanks in advance,
/* IT Engineer */

User avatar
jvierra
Posts: 12678
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: PowerShell to check file exist in the destination folder before exporting the Exchange email as .PST?

Post by jvierra » Mon Aug 20, 2018 12:55 am

Unfortunately your CSV file is not a CSV file and it does not contain names that can be piped to Get-Mailbox. You can only pipe identities to the CmdLet.

User avatar
ITEngineer
Posts: 89
Joined: Wed Oct 12, 2011 10:52 am

Re: PowerShell to check file exist in the destination folder before exporting the Exchange email as .PST?

Post by ITEngineer » Mon Aug 20, 2018 1:46 am

Hi Mr. Vierra,

Actually I have converted those names with the other lines of code to WindowsEmailAddress format, so the input is now First.Last@domain.com

Your help to assist me in this scripting would be muchly appreciated.
/* IT Engineer */

User avatar
jvierra
Posts: 12678
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: PowerShell to check file exist in the destination folder before exporting the Exchange email as .PST?

Post by jvierra » Mon Aug 20, 2018 1:50 am

Where did you do this? The code doesn't do anything like that.

User avatar
jvierra
Posts: 12678
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: PowerShell to check file exist in the destination folder before exporting the Exchange email as .PST?

Post by jvierra » Mon Aug 20, 2018 2:00 am

Using WMI to test for a file will never work. It is not like a directory listing. It cannot get UNC paths.

Use "Test-Path" to test for the file.

User avatar
ITEngineer
Posts: 89
Joined: Wed Oct 12, 2011 10:52 am

Re: PowerShell to check file exist in the destination folder before exporting the Exchange email as .PST?

Post by ITEngineer » Mon Aug 20, 2018 4:37 pm

jvierra wrote:
Mon Aug 20, 2018 1:50 am
Where did you do this? The code doesn't do anything like that.
This is the code that converts the list of First Last name into the email address into .CSV:

Code: Select all

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

User avatar
jvierra
Posts: 12678
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: PowerShell to check file exist in the destination folder before exporting the Exchange email as .PST?

Post by jvierra » Mon Aug 20, 2018 4:52 pm

Same issue. What is this: "Get-Content -Path $InputCSVPath"

You cannot .load a CSV suing Get-Content. A Csv has headers and columns. Get-Content will not convert it into anything.

What is this supposed to do?

Code: Select all

&{
	foreach ($User in $Users) {
		Write-Host "Processing.... $User"
		Get-Mailbox $User.ToString() | Select WindowsEmailAddress 
	} 
}[/code}

Is this what you are trying to do?

[code]
Get-Content -Path <text file path> |
    Get-Mailbox $_ | 
    Select WindowsEmailAddress |
    Export-Csv -Path $ExportCSVPath -NoTypeInformation
The text file must have an "identity" for each mailbox.

User avatar
ITEngineer
Posts: 89
Joined: Wed Oct 12, 2011 10:52 am

Re: PowerShell to check file exist in the destination folder before exporting the Exchange email as .PST?

Post by ITEngineer » Mon Aug 20, 2018 5:26 pm

jvierra wrote:
Mon Aug 20, 2018 4:52 pm
Same issue. What is this: "Get-Content -Path $InputCSVPath"

You cannot .load a CSV suing Get-Content. A Csv has headers and columns. Get-Content will not convert it into anything.

What is this supposed to do?
Hi Mr. Vierra,

This is the updated code that I have adapted based on your suggestion.

Code: Select all

$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
	
  }
The ExportedCSV is nicely formatted as the email address like the below:
The only error is:

Code: Select all

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
/* IT Engineer */

User avatar
ITEngineer
Posts: 89
Joined: Wed Oct 12, 2011 10:52 am

[UPDATED]: PowerShell to check file exist in the destination folder before exporting the Exchange email as .PST?

Post by ITEngineer » Mon Aug 20, 2018 11:13 pm

jvierra wrote:
Mon Aug 20, 2018 1:50 am
Where did you do this? The code doesn't do anything like that.
I have updated and minimize the error to just around the Import-Csv -Path $ExportCSVPath | Get-MailBox $_ section.

This is the updated code:

Code: Select all

$Server = 'PRDFILESVR01-VM'
$ServerBackupUNCPath = "\\$Server\PST"
$InputCSVPath = 'C:\LOGS\Input.csv'
$ExportCSVPath = 'C:\LOGS\Output.csv'
$ExportExistsCSVPath = 'C:\LOGS\Exist.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 PrimarySmtpAddress 
	} 
} | 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\$($_.PrimarySmtpAddress).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\$($_.PrimarySmtpAddress).PST" -BadItemLimit 50 -AcceptLargeDataLoss -WhatIf
	} else {
		Write-Output "The user $($_.PrimarySmtpAddress).PST file is already existing"
		#Append the list of already existing list of users C:\LOGS\Exist.csv
		Get-MailboxExportRequestStatistics -IncludeReport | Select -Expand Report | Out-File "C:\LOGS\$($_.PrimarySmtpAddress).log"
	}
	
	# I assume, whetever line I put here will be executed regardless of any of the condition above is met or not
	#Remove-Mailbox -Identity $_.PrimarySmtpAddress -Confirm $false -WhatIf
	Write-Host "Removing Mailbox $($_.PrimarySmtpAddress)" -ForegroundColor Red
  }
Here's the error message:
The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
+ CategoryInfo : InvalidArgument: (@{PrimarySmtpAd...@Domain.com}:PSObject) [Get-Mailbox], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Get-Mailbox
+ PSComputerName : PRDEXC03-VM.Domain.com
/* IT Engineer */

User avatar
jvierra
Posts: 12678
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: PowerShell to check file exist in the destination folder before exporting the Exchange email as .PST?

Post by jvierra » Mon Aug 20, 2018 11:53 pm

Its a CSV. You have to reference it correctly. We've done this many times before.

Import-Csv -Path $ExportCSVPath |
Get-MailBox $_.PrimarySmtpAddress |

Locked