Powershell:循环遍历交换查询中的名称列表

Powershell: looping through list of names from exchange query

我的目标是对新创建的邮箱应用保留策略。上一篇文章 中的详细信息。

为了便于阅读,我的当前脚本代码位于 here 或以下:

# Get Start Time for script timer
$startDTM = (Get-Date)

#Authenticate using cached credentials or re-prompt for credentials.
if (Test-Path C:\temp\mycred.xml) {
    $UserCredential = Import-CliXML C:\temp\mycred.xml}
else{
    Get-Credential | Export-CliXml C:\temp\mycred.xml
    $UserCredential = Import-CliXML C:\temp\mycred.xml}

#Connect to Exchange Server
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://munprdcasht04.exchange.com/PowerShell/ -Authentication Kerberos -Credential $UserCredential
    Import-PSSession $Session

#returns alias' for mailboxes where creation date is <= 7 days and
#resides on "ABC" or "DEF" server and has no retention policy applied
$NeedsRetentions = (Get-Mailbox -ResultSize Unlimited| Where-Object {
    ($_.WhenCreated –ge ((Get-Date).Adddays(-7))) -and
    (($_.ServerName -like "*munprdmbxa*") -or ($_.ServerName -like "*wauprdexa*")) -and
    ($_.retentionpolicy -ne "PurgeDeletedItemsFolder_60days")} |
    ft -auto alias)  

ForEach ($NeedsRetention in $NeedsRetentions){
    set-mailbox -Identity $NeedsRetention -RetentionPolicy "PurgeDeletedItemsFolder_60days"
    }

# Get End Time
$endDTM = (Get-Date)

# Echo Time elapsed
"Elapsed Time: $(($endDTM-$startDTM).totalseconds) seconds"

当我回显 $NeedsRetentions 时,我收到了我需要对其应用保留策略的 AD 用户列表。但出于某种原因,当我使用下面的循环遍历变量列表时,它会错误地指出 -Identity 无效。

ForEach ($NeedsRetention in $NeedsRetentions){
    set-mailbox -Identity $NeedsRetention -RetentionPolicy "PurgeDeletedItemsFolder_60days"
    }

为了排除故障,我将循环缩减为这样以显示受脚本影响的各个用户名:

ForEach ($NeedsRetention in $NeedsRetentions){
[System.Windows.Forms.MessageBox]::Show($NeedsRetention)
}

这样做会导致变量中的每一行都显示一个消息框,但字符串似乎是空的,因此默认消息显示在消息框中。

知道为什么 $NeedsRetention 没有正确传递到我的循环任务吗?

问题是您保存了来自 Format-*-cmdlet 的结果(在本例中 Format-Table 使用别名 ft)。

切勿将 Format-* cmdlet 的结果保存到变量中。 Format-*-cmdlet 仅用于 GUI/visual 演示,将您有用的邮箱对象转换为特殊格式对象,这些对象对其他任何东西都无用 console-/file-output。

修改:

$NeedsRetentions = (Get-Mailbox -ResultSize Unlimited| Where-Object {
    ($_.WhenCreated –ge ((Get-Date).Adddays(-7))) -and
    (($_.ServerName -like "*munprdmbxa*") -or ($_.ServerName -like "*wauprdexa*")) -and
    ($_.retentionpolicy -ne "PurgeDeletedItemsFolder_60days")} |
    ft -auto alias) 

收件人:

$NeedsRetentions = Get-Mailbox -ResultSize Unlimited| Where-Object {
    ($_.WhenCreated –ge ((Get-Date).Adddays(-7))) -and
    (($_.ServerName -like "*munprdmbxa*") -or ($_.ServerName -like "*wauprdexa*")) -and
    ($_.retentionpolicy -ne "PurgeDeletedItemsFolder_60days")}

如果您想在继续修改邮箱之前将 $NeedsRetentions 对象输出到控制台,请将其作为单独的命令执行(不保存格式输出)。例如:

$NeedsRetentions | Format-Table -AutoSize