PowerShell script to delete a Windows user account:
Here’s a PowerShell script to delete a Windows user account:
# Get the username to delete
$Username = Read-Host "Enter the username to delete"
# Confirm the deletion
$Confirmation = Read-Host "Are you sure you want to delete the user '$Username'? Type 'Y' to confirm."
if ($Confirmation -eq "Y") {
# Delete the user account
try {
# Check if the user exists
$UserExists = Get-LocalUser -Name $Username -ErrorAction Stop
if ($UserExists) {
# Remove the user
Remove-LocalUser -Name $Username
Write-Host "User account '$Username' has been deleted successfully."
}
} catch {
Write-Host "User '$Username' does not exist or an error occurred: $_"
}
} else {
Write-Host "Operation canceled."
}
Steps to run the script:
- Open PowerShell as an administrator.
- Paste the script into the PowerShell window or save it as a
.ps1
file. - Execute the script and follow the prompt to enter the username of the account you want to delete.
- Confirm the deletion by typing “Y” when prompted.
The script checks if the user exists and deletes the account. If the user doesn’t exist, it will output an error message. Let me know if you need any changes!