Quantcast
Channel: WMI – PowerShell for Windows Admins
Viewing all articles
Browse latest Browse all 140

Working with profiles: 2 deleting profiles

$
0
0

I recently (1 June) showed how to discover the user profiles on your system. Now its time to delete them.

function remove-profile {            
 param (            
  [parameter(Mandatory=$true)]            
  [string]$username            
 )            
            
 $user = Get-CimInstance -Class Win32_UserAccount -Filter "Name = '$username'"             
 $profile = Get-CimInstance -Class Win32_UserProfile -Filter "SID = '$($user.SID)'"            
 $folder = Split-Path -Path $profile.LocalPath -Leaf            
            
 if ($folder -eq $username){            
  Remove-CimInstance -InputObject $profile            
 }            
 else {            
  Write-Warning -Message "Could not resolve profile and user name"             
 }            
            
}

I’m going to start with the CIM cmdlets as these are the way of the future in PowerShell v3.

Start by taking a user name as a parameter. Get the Win32_UserAccount class object representing that account. use the SID to find the profile via Win32_UserProfile.  Take the profile’s localpath and split it. The last part of the path should match the username – if it does then delete the profile otherwise throw a warning. Deleting the profile does delete the folder under c:\users

If you have to use the WMI cmdlets then its very similar

function remove-profile {            
 param (            
  [parameter(Mandatory=$true)]            
  [string]$username            
 )            
            
 $user = Get-WmiObject -Class Win32_UserAccount -Filter "Name = '$username'"             
 $profile = Get-WmiObject -Class Win32_UserProfile -Filter "SID = '$($user.SID)'"            
 $folder = Split-Path -Path $profile.LocalPath -Leaf            
            
 if ($folder -eq $username){            
  Remove-WmiObject -InputObject $profile            
 }            
 else {            
  Write-Warning -Message "Could not resolve profile and user name"             
 }            
            
}

Just the name of the cmdlets change.

You can’t use WMI to delete local accounts as explained on page 363 of PowerShell and WMI 

If you have profiles generated by AD accounts you’ll need to find the SID from the AD account and use that as the filter for deletion


Viewing all articles
Browse latest Browse all 140

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>