Перейти к содержимому

Как создать переадресацию с одного ящика на другой в exchange. Переезд в другой домен.

Задача. Есть два домена. Из одного домена люди перешли в другой. Нужно настроить переадресацию писем из одного домена в другой.

Скрипт вытягивает пользователей из домена adminbd1 находит соответствие в adminbd2 и создаёт правило пересылки.

<# .SYNOPSIS
    Создание переадресации писем сотрудников adminbd1 с adminbd2 на adminbd1
.DESCRIPTION
    Скрипт вытягивает пользователей из домена adminbd1 находит соответствие в adminbd2 и создаёт правило пересылки.
#>
#╔════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗#
$Host.UI.RawUI.WindowTitle = "Создание переадресации писем с adminbd2 на adminbd1"
#╚════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝#
[system.gc]::Collect()
$ErrorActionPreference="Continue"
#------ Logging section ------#
 
#$dp0 = ($MyInvocation.MyCommand.Path | Split-Path -Parent)
$fileLocation = (gi $MyInvocation.InvocationName) | ForEach-Object {
    $fileDirectory = "$($_.DirectoryName)\$($_.BaseName)";
    "$fileDirectory\$($_.BaseName)_$('{0:yyyy-MM-dd}'-f(date))";
    if (!(Test-Path "$fileDirectory")) {
        ni "$fileDirectory" -ItemType "directory" | Out-Null
    }
}
#$watch = [System.Diagnostics.Stopwatch]::StartNew()
#$watch.Start()
#Start-Transcript "${fileLocation}.log" -append
 
$detailed = [ordered]@{
    DisplayName = ""
    Mail    = ""
    Contact = ""
    #AddressLists = ""
    Error   = ""
}
 
#------ Variables ------#
$Result = @()
$tAD = 'DisplayName','title','company','department','mailNickname','Office','l','givenName','sn','telephoneNumber','Mobile','mail','enabled','SamAccountName'
$UO = "OU=Locations,DC=adminbd1,DC=pro"
$ExceptinUsers = 'Ivan.Ivanovich'
 
#------ Establishing a connection ------#
 
#$UserCredential = Get-Credential
$UserCredential = Import-CliXML -Path 'D:\Programs\Scripts\ForwardingAddress\mycredentials_adminbd1.xml'
$Sessionadminbd1 = New-PSSession -ComputerName ad03.adminbd1.pro -Authentication Kerberos -Credential $UserCredential
#$Usersadminbd1 = Invoke-Command -Session $Sessionadminbd1 -ScriptBlock {Get-ADUser -Identity test -Properties $Using:tAD | select $Using:tAD}
$Usersadminbd1 = Invoke-Command -Session $Sessionadminbd1 -ScriptBlock {
    Get-ADUser -SearchBase $Using:UO -Filter {Enabled -eq "True"} -Properties $Using:tAD | select $Using:tAD |
    Where-Object    {
        !($(foreach ($u in $Using:ExceptinUsers) {$_.SamAccountName -Contains  $u}) -contains ($True))
    }  
}
Remove-PSSession $Sessionadminbd1
 
 
#$UserCredential = Get-Credential
$UserCredential = Import-CliXML -Path 'D:\Programs\Scripts\ForwardingAddress\mycredentials_adminbd2.xml'
#$Sessionadminbd2 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://MXS01.adminbd2.ru/PowerShell/ -Authentication Kerberos
$Sessionadminbd2 = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://MXS01.adminbd2.ru/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Sessionadminbd2 -DisableNameChecking -AllowClobber
 
ForEach ($user in $Usersadminbd1)   {
     
    if (Get-MailContact ($user.displayname + " - arn").ToString()) {
        $detailed.Contact = "Contact exists"
    #}
   #Создаём пересылку
        if (Get-Mailbox $user.SamAccountName){
            #Set-Mailbox -ForwardingAddress $user.Mail -Identity $user.SamAccountName #-WhatIf
            New-TransportRule $user.DisplayName -SentTo ($user.displayname + " - vx").ToString() -RedirectMessageTo $user.Mail | Out-Null          
            $detailed.DisplayName = $user.DisplayName
            $detailed.Mail = $user.Mail
        } else {   
            $detailed.Mail = "Mail no exists"
        }
    } else {
        $detailed.Contact = "Contact no exists"
    }
 
#------ Error ------#
 
    if ($detailed.Error -eq "") {
        $Error.Clear()
 
        if($Error[0]) {
            #Write-Host "Error logged"
            foreach ($E in $Error) {
                $detailed.Error += $E.Exception.Message
            }
        } else {
            $detailed.Error = "No error"
        }
    }
 
    #if ($detailed.Error -eq "") {
        #$detailed.Error = "No error"
    #}
 
    $Result += New-Object PSObject -Property $detailed
 }
 
#------ Finishing ------#
 
write-host 'Finishing is Completed'
Remove-PSSession $Sessionadminbd2
 
$Result | Export-CSV -Path "$fileLocation" -NoTypeInformation -Append -Force -Encoding "UTF8" -Delimiter ";"
<#
$watch.Stop()
'Время выполнения ' + [string]$watch.Elapsed  #Остановка таймера  #Время выполнения
Stop-Transcript
#>

 

Similar Posts:

Метки:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *