onsdag den 15. april 2015

Remove local userprofile from a machine remote

Apparently some people are looking for a way to remove local user profiles from computers remotely. Of course Powershell is the perfect tool for that. Here is an initial script for just that. Feel free to use and modify :-)

Function Remove-LocalProfile
{
<#
.SYNOPSIS
Removes a local userprofile from a computer
.DESCRIPTION
Removes a specific local userprofile from a computer. The profile can only be removed, if the user has not been locked on since last reboot.
.EXAMPLE
Remove-LocalProfile -Computer YourComputer -Samaccountname YourUser
Removes the local profile for YourUser on YourComputer
#>
[CmdletBinding()]
param
(
[parameter(Mandatory=$true,Position=0)]$Computer,
[parameter(Mandatory=$true,Position=1)]$SamAccountName
)
try
{
$Sid = Get-ADUser $SamAccountName | select -expand sid | select -expand value
}
Catch
{
Write-Warning "$SamAccountName not found in AD"
Break
}
if (Test-Connection $computer -Count 1 -Quiet)
{
$Profile = Get-WmiObject Win32_UserProfile -ComputerName $Computer | where {$_.SID -eq $Sid}
if ($Profile)
{
Try
{
Write-Verbose "Removing $SamAccountName from $Computer"
$Profile.delete()
}
catch
{
Write-Warning "The Profile of $SamAccountName is locked. Please restart $Computer and try again."
}
}
else
{
Write-Warning "$SamAccountName not found on $Computer"
}
}
else {Write-Warning "$Computer is not online"}
}