Скрипт вытягивает пользователей из домена adminbd.ru и создаёт их контакты в домене adminbd2.ru . Так же прячет одноимённую почту домена adminbd2.ru
При создание файла с данными для входа $UserCredential = Import-CliXML -Path ‘D:\Programs\Scripts\Import_contact-arn_to_vx\mycredentials_adminbd.xml’ важно генерировать файл от того пользователя от которого будет производится запуск крипта.
<# .SYNOPSIS
Заведение контактов - adminbd.ru to adminbd2.ru
.DESCRIPTION
Скрипт вытягивает пользователей из домена adminbd.ru и создаёт их контакты в домене adminbd2.ru. Так же прячет одноиённую почту домена adminbd2.ru.
#>
#╔════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗#
$Host.UI.RawUI.WindowTitle = "Заведение контактов - adminbd.ru to adminbd2.ru"
#╚════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝#
[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=adminbd.ru,DC=pro"
$ExceptinUsers = 'Ivan.Ivanovch'
#------ Establishing a connection ------#
#$UserCredential = Get-Credential
$UserCredential = Import-CliXML -Path 'D:\Programs\Scripts\Import_contact-arn_to_vx\mycredentials_adminbd.ru.xml'
$Sessionadminbd.ru = New-PSSession -ComputerName ad03.adminbd.ru.pro -Authentication Kerberos -Credential $UserCredential
#$Usersadminbd.ru = Invoke-Command -Session $Sessionadminbd.ru -ScriptBlock {Get-ADUser -Identity kirill.mikhalchuk -Properties $Using:tAD | select $Using:tAD}
$Usersadminbd.ru = Invoke-Command -Session $Sessionadminbd.ru -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 $Sessionadminbd.ru
#$UserCredential = Get-Credential
$UserCredential = Import-CliXML -Path 'D:\Programs\Scripts\Import_contact-arn_to_vx\mycredentials_adminbd2.ru.xml'
#$Sessionadminbd2.ru = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://MXS01.adminbd2.ru.ru/PowerShell/ -Authentication Kerberos
$Sessionadminbd2.ru = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://MXS01.adminbd2.ru.ru/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Sessionadminbd2.ru -DisableNameChecking -AllowClobber
ForEach ($user in $Usersadminbd.ru) {
#Прячем почту
if (Get-Mailbox $user.SamAccountName){
Set-Mailbox -HiddenFromAddressListsEnabled $true -Identity $user.SamAccountName | Out-Null
$detailed.AddressLists = "true"
#}
#Пользователь заблокирован?
if ($user.enabled -eq $false) {
#У пользователя есть почта?
if ($user.mail -notlike $NULL) {
#Пользователь заблокирован, удаляем существующий контакт
Remove-MailContact $user.mail –Confirm:$false
}
}
elseif ($(Get-contact $user.displayname)) {
#elseif ($True) {
if ($user.mail -notlike $NULL) {
#Пользователь не заблокирован, контакт существует, надо обновить
Set-Contact $user.mail -Company "adminbd.ru" -Title $user.Title -Department $user.Department -Mobile $user.mobile -firstname $user.GivenName -Phone $user.telephoneNumber -lastname $user.sn -city $user.l
}
}
else {
if ($user.mail -notlike $NULL) {
#Пользователь не заблокирован, контакт не существует, надо создать
New-MailContact -Name ($user.displayname + " - arn").ToString() -DisplayName $user.displayname -alias ($user.mailNickname + ".adminbd.ru").ToString() -OrganizationalUnit adminbd2.ru.ru/Contacts/adminbd.ru -ExternalEmailAddress $user.mail
$detailed.Contact = "create"
$detailed.DisplayName = $user.DisplayName
$detailed.Mail = $user.mail
}
}
}
#------ 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.ru
$Result | Export-CSV -Path "$fileLocation" -NoTypeInformation -Append -Force -Encoding "UTF8" -Delimiter ";"
<#
$watch.Stop()
'Время выполнения ' + [string]$watch.Elapsed #Остановка таймера #Время выполнения
Stop-Transcript
#>
Similar Posts:
- Как создать переадресацию с одного ящика на другой в exchange. Переезд в другой домен.
- Как завести пользователь в exchange через powershell.
- Как сделать автоматическое создание почтовых ящиков с отключёнными ActiveSync и MAPI и добавить в группу G-Deny to send
- Как сделать автоматическую очистку почты exchange при заполнении больше 90 процентов ящика.
- Как сделать автоматическое создание почтового ящика exchange.