Search code examples
powershellexchange-server-2010

Execute a cmdlet within a ForEach query


I am attempting to run the following PowerShell command against my Exchange 2010 SP1 server:

$colItems = Get-Mailbox -Filter {office -eq "ExportPST"}
ForEach($objItem in $colItems)
{
New-MailboxExportRequest -Mailbox $objItem -FilePath \\server\share$\"$objItem".pst
}

When I do this I receive the error:

Couldn't locate a database suitable for storing this request. + CategoryInfo : InvalidArgument: (domain.com....d/John Doe:MailboxOrMailUserIdParameter) [New-M ailboxExportRequest], MailboxDatabase...manentException + FullyQualifiedErrorId : 9322CB6D,Microsoft.Exchange.Management.RecipientTasks.NewMailboxExportRequest

What I am attempting to do is search across my AD users, locate users that have the string ExportPST in the Office field, and then export the command New-MailboxExportRequest to export the entire contents of the user's mailbox to a PST for each user returned.

When I add a Write-Host to the above, the outputed values are correct:

New-MailboxExportRequest -Mailbox jdoe -FilePath " \\server\share$\John Doe.pst"

The output also includes an extra space between the -FilePath " and \, which I imagine will cause an issue once the above issue has been resolved, is there a way to contactenate strings without it adding this extra space?

Thanks,

Matt


Solution

  • I think your quoting is a bit off. Double-quoted string expansion works when you completely surround the string, not just the variable part.

    $colItems = Get-Mailbox -Filter {office -eq "ExportPST"}
    ForEach($objItem in $colItems)
    {
      New-MailboxExportRequest -Mailbox $objItem -FilePath "\\server\share$\$objItem.pst"
    }
    

    Here's an alternative syntax which uses .NET string formatting / replacement:

    $colItems = Get-Mailbox -Filter {office -eq "ExportPST"}
    ForEach($objItem in $colItems)
    {
      New-MailboxExportRequest -Mailbox $objItem -FilePath ('\\server\share$\{0}.pst' -f $objItem)
    }
    

    To make troubleshooting / debugging easier, you could assign the file path to a variable, and then pass the variable into the -FilePath parameter. That way you can see exactly which value is getting passed in.

    $colItems = Get-Mailbox -Filter {office -eq "ExportPST"}
    ForEach($objItem in $colItems)
    {
      $FilePath = '\\server\share$\{0}.pst' -f $objItem;
      Write-Host -Object ('$FilePath value is: {0}' -f $FilePath);
      New-MailboxExportRequest -Mailbox $objItem -FilePath $FilePath;
    }