===== PowerShell скрипт для отключения учетных записей пользователей (по списку из файла) в Active Directory =====
{{.:pasted:20250522-152145.png }} Приводим пример **PowerShell** скрипта, который отключает учетные записи пользователей в домене **Active Directory** на основе списка из файла:
<#
.SYNOPSIS
Disables user accounts in AD based on a list from a file.
.DESCRIPTION
This script reads a list of users from a text file and
disables their accounts in Active Directory.
Each line of the file should contain the user's SAMAccountName (login).
.PARAMETER FilePath
Path to the file containing the list of users.
.PARAMETER LogPath
Path to the log file (optional).
.EXAMPLE
.\Disable-ADUsersFromFile.ps1 -FilePath "C:\users.txt" -LogPath "C:\disable_log.txt"
#>
param (
[Parameter(Mandatory=$true)]
[string]$FilePath,
[string]$LogPath
)
# Check if ActiveDirectory module is available
if (-not (Get-Module -Name ActiveDirectory -ErrorAction SilentlyContinue)) {
try {
Import-Module ActiveDirectory -ErrorAction Stop
}
catch {
Write-Error "ActiveDirectory module is not installed. Please install RSAT Tools."
exit 1
}
}
# Verify the existence of the user list file
if (-not (Test-Path -Path $FilePath)) {
Write-Error "File $FilePath not found."
exit 1
}
# Logging function
function Write-Log {
param (
[string]$Message
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logMessage = "[$timestamp] $Message"
if ($LogPath) {
Add-Content -Path $LogPath -Value $logMessage
}
Write-Output $logMessage
}
Write-Log "Script execution started"
# Read user list from file
try {
$users = Get-Content -Path $FilePath -ErrorAction Stop | Where-Object { $_ -match '\S' }
$userCount = $users.Count
Write-Log "Found $userCount users to process in file $FilePath"
}
catch {
Write-Log "Error reading file $FilePath : $_"
exit 1
}
$disabledCount = 0
$notFoundCount = 0
$errorsCount = 0
# Process each user
foreach ($user in $users) {
$user = $user.Trim()
if ([string]::IsNullOrEmpty($user)) {
continue
}
Write-Log "Processing user: $user"
try {
# Search for user in AD
$adUser = Get-ADUser -Filter "SamAccountName -eq '$user'" -ErrorAction Stop
if ($adUser) {
# Check if account is already disabled
if ($adUser.Enabled -eq $false) {
Write-Log "Account $user is already disabled"
$notFoundCount++
}
else {
# Disable the account
Disable-ADAccount -Identity $adUser -ErrorAction Stop
Write-Log "Account $user successfully disabled"
$disabledCount++
}
}
else {
Write-Log "User $user not found in AD"
$notFoundCount++
}
}
catch {
Write-Log "Error processing user $user : $_"
$errorsCount++
}
}
Write-Log "Processing completed"
Write-Log "Summary:"
Write-Log " - Successfully disabled: $disabledCount"
Write-Log " - Not found in AD: $notFoundCount"
Write-Log " - Errors: $errorsCount"
**Инструкция по использованию:**
- Скопируйте скрипт в файл с расширением .ps1 (например, Disable-ADUsersFromFile.ps1) в кодировке UTF-8
- Подготовьте текстовый файл со списком пользователей (по одному в каждой строке), например users.txt:
user1
user2
user3
- Запустите PowerShell от имени администратора, имеющего доступ к упралению учётными записями в AD
- Выполните скрипт, указав имя файла со списком пользователей и имя файла логирования процесса отключения:
.\Disable-ADUsersFromFile.ps1 -FilePath "C:\path\to\users.txt" -LogPath "C:\path\to\log.txt"
Параметр -LogPath не является обязательным. Если он не указан, результат будет выводиться только в консоль.
**Особенности скрипта:**
* Требует PowerShell 5.1 или новее и PS-модуль ActiveDirectory (часть RSAT)
* Требует права на отключение учетных записей в домене
----
Проверено на следующих конфигурациях:
^ Версия ОС ^ Версия Powershell ^
| Microsoft Windows 11 Pro 24H2 10.0.26100 | PowerShell 5.1.26100.2161 |
----
{{:user:blogroot.png?50&nolink |}} Автор первичной редакции:\\ [[user:blogroot|Алексей Максимов]] \\ Время публикации: 22.05.2025 16:24
{{tag>PowerShell ADDS "Active Directory" }}
~~DISCUSSION~~