Skip to content

Instantly share code, notes, and snippets.

@noelruault
Created June 26, 2024 09:45
Show Gist options
  • Save noelruault/ed849062cec74e0f4a37173f5f972fcf to your computer and use it in GitHub Desktop.
Save noelruault/ed849062cec74e0f4a37173f5f972fcf to your computer and use it in GitHub Desktop.
$excludedUsers = @("Admin", "Administrator")
Function Remove-LocalUser {
<#
.Synopsis
This function deletes a local user
.Description
This function deletes a local user
.Example
Remove-LocalUser -userName "ed"
Removes a new local user named ed.
.Parameter ComputerName
The name of the computer upon which to delete the user
.Parameter UserName
The name of the user to delete
.Notes
NAME: Remove-LocalUser
AUTHOR: ed wilson, msft
LASTEDIT: 06/29/2011 10:07:42
KEYWORDS: Local Account Management, Users
HSG: HSG-06-30-11
.Link
Http://www.ScriptingGuys.com/blog
#Requires -Version 2.0
#>
[CmdletBinding()]
Param(
[Parameter(Position=0,
Mandatory=$True,
ValueFromPipeline=$True)]
[string]$userName
)
$computerName = $env:ComputerName
$User = [ADSI]"WinNT://$computerName"
$user.Delete('user',$userName)
} #end function Remove-LocalUser
$localUsers = Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True'" | Select-Object -ExpandProperty Name
foreach ($localUser in $localUsers) {
if ($excludedUsers -contains $localUser -or $excludedUsers -contains $localUser.ToUpperInvariant() -or $excludedUsers -contains $localUser.ToLowerInvariant()) {
Write-Host "Skipping user: $localUser"
} else {
Write-Host "Removing user: $localUser"
Remove-LocalUser -userName $localUser
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment