搜索邮箱 powershell 脚本未按预期工作

search-mailbox powershell script not working as expected

如果我将直接 powershell 与交换模块一起使用,一切都会按预期工作:

echo $mbxs | Search-Mailbox -SearchQuery 'received:01/07/2020..01/08/2020 AND from:test@some.com' -DeleteContent -Force

但是如果我使用 ps1 脚本,我会得到 KQL 异常:

$date01=(get-date).AddDays(-14).ToString("dd\/MM\/yyyy")
$date02=(get-date).AddDays(-28).ToString("dd\/MM\/yyyy")
$mails = "test@some.com","test1@some.com"
$mbxs = import-csv C:\script\names.csv
foreach ($mail in $mails) 
{
    echo $mbxs | Search-Mailbox -SearchQuery 'received:$date02..$date01 AND from:$mail' -DeleteContent -Force
    echo $mbxs | Search-Mailbox -SearchQuery 'sent:$date02..$date01 AND to:$mail' -DeleteContent -Force
}
Remove-Variable mbxs,mails,date01,date02

The KQL parser threw an exception.

相同的脚本在 2003 服务器上的 ps 1.0 上运行,但在 2012 R2 上不起作用...我做错了什么?

我发现了几个问题:

  1. 字符串中的变量需要用双引号展开:
  2. 如果您从 CSV 导入,则必须参考 属性。
  3. 您不需要在管道中回显 $mbxs。你应该可以直接说出来。

它应该看起来像这样:

$date01=(get-date).AddDays(-14).ToString("dd\/MM\/yyyy")
$date02=(get-date).AddDays(-28).ToString("dd\/MM\/yyyy")
$mails = "test@some.com","test1@some.com"
$mbxs = import-csv C:\script\names.csv
foreach ($mail in $mails) 
{
    $mbxs | Search-Mailbox -SearchQuery "Received:$date02..$date01 AND From:$mail" -DeleteContent -Force
    $mbxs | Search-Mailbox -SearchQuery "Sent:$date02..$date01 AND To:$mail" -DeleteContent -Force
}
Remove-Variable mbxs,mails,date01,date02

不过,我也有点担心,因为如果您从 CSV 导入,您通常必须引用 属性。如果您想要 post CSV 数据的代表性样本,我们可以对其进行更正。