Hi Ilya,
I Prepare something for you, the logic works(Also you can verify that without the exchange cmdlets)
Import-Module ActiveDirectory
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn
$users = import-csv "C:\csv\СписокУволенныхСотрудников.csv"
function exportMailbox {
param (
$sam
)
New-MailboxExportRequest -Mailbox $sam `
-Name $user -FilePath \exchange\fired$sam.pst
}
function getDgroups {
param (
$sam
)
$groups=`
$(Get-DistributionGroup -ResultSize Unlimited | Where-Object { $_.Members -like "*,$($sam)" })
$groupMemberships = $groups | Select-Object Name
return $groupMemberships
}
function disableuser {
param (
$sam
)
Write-Host("Disable identity "+$sam)
Disable-ADAccount -Identity $sam
Write-Host("Move to OU disable "+$sam)
Get-ADUser -Identity $sam | Move-ADObject -TargetPath "OU=DisabledAcounts,DC=next,DC=local"
$fileName = $sam+"PST"
if ((Get-MailboxExportRequest $fileName).Status -eq "Completed") {
Write-Host("Disable and remove mailbox"+$sam)
Disable-Mailbox -Identity $sam -confirm:$false
Get-MailboxExportRequest -Status Completed | Remove-MailboxExportRequest -Confirm:$false
}
}
foreach ($user in $users){
Write-Host("Get SamaccountName "+$user.name)
$username = Get-ADUser -Filter 'Name -eq $UserName' | Select-Object sAMAccountName
exportMailbox($username)
$groups=getDgroups($username)
foreach ($group in $groups) {
Remove-DistributionGroupMember -Identity $group -Member $($username) -Confirm:$false
Write-Host("removing "+$username+" from group: "+$group)
}
disableuser($username)
}
Verify and customize with your requirement and let me know any question.
Cheers,
Luis Arias
If the information helped address your question, please Accept the answer.