<#
.SYNOPSIS
Clear Home Folder (local path) for each AD user in an OU and export results to CSV.
.PARAMETER SearchBase
Distinguished Name (DN) of the OU to search.
.PARAMETER WhatIfMode
If supplied, no changes are actually made.
.PARAMETER CsvPath
Output path for the CSV file.
#>
param(
[string]$SearchBase = 'OU=.Users (Role Based),OU=Steven Whiting,DC=whiting-steven,DC=co,DC=uk',
[switch]$WhatIfMode,
[string]$CsvPath = ".\HomeFolder_Clear_Report_$(Get-Date -Format yyyyMMdd_HHmmss).csv"
)
# Import AD module
Import-Module ActiveDirectory -ErrorAction Stop
Write-Output "SearchBase: $SearchBase"
if ($WhatIfMode) { Write-Output "WHATIF MODE ENABLED — no changes will be made." }
# Retrieve users
$users = Get-ADUser -Filter * -SearchBase $SearchBase -SearchScope Subtree -Properties homeDirectory,homeDrive,DistinguishedName,SamAccountName
if (-not $users) {
Write-Output "No users found under the specified OU."
exit
}
# Results array
$results = @()
foreach ($u in $users) {
$result = [PSCustomObject]@{
SamAccountName = $u.SamAccountName
DistinguishedName = $u.DistinguishedName
PreviousHomeDirectory = $u.homeDirectory
PreviousHomeDrive = $u.homeDrive
Action = ""
}
if ($WhatIfMode) {
$result.Action = "Would Clear"
$results += $result
continue
}
try {
Set-ADUser -Identity $u.DistinguishedName -Clear homeDirectory,homeDrive -Confirm:$false -ErrorAction Stop
$result.Action = "Cleared"
} catch {
$result.Action = "Failed: $($_.Exception.Message)"
}
$results += $result
}
# Export CSV
$results | Export-Csv -NoTypeInformation -Path $CsvPath
Write-Output "CSV report created: $CsvPath"
Write-Output "Completed."