通过PowerShell批量创建转发地址和联系人

时间:2015-12-09 20:15:48

标签: powershell exchange-server office365 powershell-v3.0

我正在尝试将邮箱移动到另一个O365租户上的新Exchange服务器。此脚本是此移动的一部分,它尝试列出拥有许可证的所有Exchange Online用户,为每个指向其新电子邮件地址的用户创建联系人,并将其电子邮件转发到新地址及其邮箱

#requires -Version 3 -Modules MSOnline
$mailboxlist = Get-Mailbox | Select-Object -Property userprincipalname | 
Get-MsolUser | Where-Object -Property islicensed -EQ -Value $true | 
Select-Object -Property firstname, lastname, userprincipalname | 
Where-Object -Property firstname -NE -Value $null | 
Format-list -AutoSize


#Begin foreach loop
foreach ($item in $mailboxlist)
{
   #Create the forwarding address
   $forwardingaddress = $item.firstname + '.' + $item.lastname + '@newdomain.com'
   #Check for a contact, add if not present
   If (!(Get-MailContact $forwardingaddress -ErrorAction silentlycontinue)){
        New-MailContact $forwardingaddress -ExternalEmailAddress $forwardingaddress
   }
   #assign forwarding address
   set-mailbox -ForwardingAddress $forwardingaddress -DeliverToMailboxAndForward $true

}

上面的结果是$ mailboxlist,其中填充了名字和姓氏以及用户UPN,它也是一个电子邮件地址。 $ forwardingaddress的结果是。@ newdomain.com。

我认为我没有为foreach循环正确创建初始数据。我知道如果我用$ _。firstname替换$ item.firstname,我会得到相同的空结果。如果对该主题有所了解的人可以提供帮助,我将不胜感激。

谢谢!

编辑:使用Kiran建议的最终配置

#requires -Version 3 -Modules MSOnline
$mailboxlist = Get-Mailbox |  Get-MsolUser | Where-Object { ($_.islicensed -eq $true) -and ($_.firstname -ne $null) }


#Begin foreach loop
foreach ($item in $mailboxlist)
{
    #Create the forwarding address
    $forwardingaddress = $item.firstname + '.' + $item.lastname + '@newdomain.com'
    #Remove any spaces from the email address
    $forwardingaddress = ($forwardingaddress -replace " ","").trim()
    #Check for a contact, add if not present
    If (!(Get-MailContact $forwardingaddress -ErrorAction silentlycontinue))
    {
        New-MailContact $forwardingaddress -ExternalEmailAddress $forwardingaddress
    }
    #assign forwarding address
    Set-Mailbox -ForwardingAddress $forwardingaddress -DeliverToMailboxAndForward $true
}

1 个答案:

答案 0 :(得分:1)

try this:

$mailboxlist = Get-Mailbox |  Get-MsolUser | 
    Where-Object { ($_.islicensed -eq $true) -and ($_.firstname -ne $null) } 

the UserPrincipalName of get-Msoluser accepts pipeline input by propertyname so you should just pipe the output of get-mailbox to get-msoluser

select-object should be preferred over format-* commands because of the type of objects that are created.

Use format* when you want to show data on the console.

The where-object clause allows you to create complex conditions so try to combine them where you can. This should be the flow of commands:

cmdlet | where-object { some condition(s)} | select properties