Export PST via powershell script

Hi!

I have a command I use frequently and would like to script it out:

New-MailboxExportRequest -Mailbox "User" -ContentFilter {Subject -like "*Distorted*"} -FilePath "\\filepath\c$\temp\User.pst"

When I run the above, I get a PST where i can see the email I am looking for. When I add the same command, with variables, to my script I get my PST with folders, but no emails.

[string]$mailbox = Read-Host 'Search Mailbox User'
[string]$subject = Read-Host 'Email Subject'
New-MailboxExportRequest -Mailbox "$mailbox" -ContentFilter {Subject -like "$subject"} -FilePath "\\filepath\c$\temp\$mailbox-$subject.pst"

I have tried single/double quotes, nixing quotes for $mailbox and $subject with no success. Is there a better/cleaner way to do this, or am I making a typo I don't see? Thanks for any and all help!

Posted Feb 27, 2019, 8:47 PM UTC

13
XxRedrum•

Try "$($subject)" inside your script block.

Also (imo) you should add a read-host for the file path, you could make it not required, but if you supply it then you can save it somewhere else.

1
physpherOP•

Thanks! When I get back to my computer, I'll take a stab at it! Do we want to try this because of the way exchange handles variables, or is this a preferred method in general? I'm not much of a scripter, but if this works, I'd love to semi-automate a few more mundane tasks that come across my desk frequently.

2
XxRedrum•

Indeed, in the context of "...", an expandable string (interpolating string):

You do NOT need $(...) with a simple variable reference such as:

$taskTitle or $env:HOME

Sometimes you must (or may choose to) use the form ${taskTitle} or ${env:HOME} - i.e., {...} around the identifier - so as to disambiguate the variable name from subsequent characters in the string.

You DO need $(...) for anything else:

accessing a property; e.g.:

"count is: $($var.Count)"

embedding an expression; e.g.:

"path prefix: $($var + '/')"

embedding entire commands (possibly even multiple ones); e.g.:

"file names: $(Get-ChildItem *.txt | Select-Object -ExpandProperty Name)"
1