Skip to content

Instantly share code, notes, and snippets.

@kenpb
Created December 11, 2015 00:50
Show Gist options
  • Save kenpb/ccb5f5ab57e7ce79b3b2 to your computer and use it in GitHub Desktop.
Save kenpb/ccb5f5ab57e7ce79b3b2 to your computer and use it in GitHub Desktop.
function Remove-LocalUserProfile {
<#
.SYNOPSIS
Removes a local user profile from the local or remote computer.
.DESCRIPTION
Removes a local user profile from the local or a remote computer by getting the Win32_UserProfile WMIObject, translating the SIDs to
usernames, and removing the profile if the result matches the specified username.
.PARAMETER ComputerName
Name of the computer you want to remove the user from.
.PARAMETER User
Name of the user you want to remove from the computer.
.EXAMPLE
Remove-LocalUserProfile -ComputerName localhost -User shwnstrmn
.NOTES
Written by https://www.reddit.com/u/saGot3n from the post https://www.reddit.com/r/PowerShell/comments/3rhssc/functions_and_getwmiobjects/.
Modified by Shawn Esterman on November 4, 2015.
#>
[CmdletBinding(ConfirmImpact="High")]
param (
# Paramter Computername
[Parameter(Mandatory=$true,
HelpMessage="Name of the computer you want to remove the user from.")]
[String]
$ComputerName,
# Paramter User
[Parameter(Mandatory=$true,
HelpMessage="Name of the user you want to remove from the computer.")]
[String]
$User
)
Begin {
function CompareSIDToSamAccountName ( [String] $SID, [String] $SamAccountName ) {
try {
$SecurityIdentifier = New-Object System.Security.Principal.SecurityIdentifier($SID) -ErrorAction SilentlyContinue
$NTAccount = $SecurityIdentifier.Translate([System.Security.Principal.NTAccount])
$Username = $NTAccount.Value.Split("\")[1]
if ( $Username -eq $SamAccountName ) { return $true } else { return $false }
}
catch { return $false }
} # Close function CompareSIDToSamAccountName
} # Close Begin block
Process {
$Win32_UserProfile = Get-WmiObject Win32_UserProfile -ComputerName $ComputerName | Where-Object -FilterScript { CompareSIDToSamAccountName -SID $_.SID -SamAccountName $User }
if ( $Win32_UserProfile ) {
try {
if ( $PSCmdlet.ShouldProcess( $ComputerName, "Removing local profile for $User" ) ) {
$Win32_UserProfile.Delete()
}
}
catch {
Write-Warning -Message ( "Failed to remove the profile for the user $User on $ComputerName.This can occur when the`n" +
"user is still logged in. Try restarting the computer and trying again." )
}
} else {
Write-Warning -Message ( "There was no profile found for the user $User on $ComputerName. You should confirm that this does`n" +
"not exist. Before continuing." )
}
} # Close Process block
End {} # Close End block
} # Close function Remove-LocalUserProfile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment