src/Public/Remove-ADUsersByOU.ps1
|
<#
.SYNOPSIS Removes all users from a specified Active Directory Organizational Unit (OU) along with their home and profile folders. .DESCRIPTION This function searches for a specified OU and removes all users within it. It also deletes their home and profile folders if they exist. .PARAMETER ouName The name of the Organizational Unit (OU) from which users will be removed. .EXAMPLE Remove-ADUsersFromOU -ouName "YourOUNameHere" .NOTES Author: Your Name Date: Today's Date #> function Remove-ADUsersFromOU { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0, ParameterSetName = 'Name')] [ValidateNotNullOrEmpty()] [string]$ouName, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'DistinguishedName')] [ValidateNotNullOrEmpty()] [string]$ouDistinguishedName, [Parameter(Mandatory = $false)] [switch]$DoNotRemoveFiles ) begin { Write-Verbose "Starting function Remove-ADUsersFromOU" } process { try { # Search for the OU If ( $ouName) { $ou = Get-ADOrganizationalUnit -Filter "Name -eq '$ouName'" | Select-Object -ExpandProperty DistinguishedName If ($OU.count -gt 1) { Write-Warning "Multiple OUs found with the name '$ouName'. Please specify a unique OU name." return } } else { If (Get-AzADOrganizationalUnit -DistinguishedName $ouDistinguishedName) { $ou = $ouDistinguishedName } else { Write-Warning "OU with DistinguishedName '$ouDistinguishedName' not found." return } } if ($ou) { Write-Verbose "Found OU: $ou" # Get all users in the specified OU $users = Get-ADUser -Filter * -SearchBase $ou -Properties SamAccountName, HomeDirectory, ProfilePath foreach ($user in $users) { $homeFolder = $user.HomeDirectory $profileFolder = $user.ProfilePath # Remove the user's home and profile folders if (-not $DoNotRemoveFiles) { if ($homeFolder -and (Test-Path $homeFolder)) { Remove-Folder -Path $homeFolder -Force } if ($profileFolder -and (Test-Path "$profileFolder.v6")) { Remove-Folder -Path $profileFolder -Force } } # Check if both folders are removed if (($homeFolder -and -not (Test-Path $homeFolder)) -and ($profileFolder -and -not (Test-Path $profileFolder))) { # Remove the user from Active Directory Remove-ADUser -Identity $user -Confirm:$false Write-Verbose "Removed user $($user.SamAccountName)" } else { Write-Warning "Failed to remove folders for $($user.SamAccountName)" } } } else { Write-Warning "OU '$ouName' not found." } } catch { Write-Error "An error occurred: $_" } } end { Write-Verbose "Ending function Remove-ADUsersFromOU" } } |