Working with profiles: part 1
A question came up on the forum for PowerShell and WMI – how do I delete profiles. I’m going to work up to answering that by looking at using WMI to work with profiles.
So to start how can we find the profiles available on our system
Get-WmiObject -Class Win32_UserProfile |
select LocalPath, SID, @{N="LastUseTime"; E={$_.ConvertToDateTime($_.LastUseTime)}}
LocalPath SID LastUseTime
--------- --- -----------
C:\Users\Richard S-1-5-21-2542198769-1191... 01/06/2012 19:56:28
C:\Windows\ServiceProfil... S-1-5-20
C:\Windows\ServiceProfil... S-1-5-19
C:\Windows\system32\conf... S-1-5-18
or if you prefer the CIM cmdlets in PowerShell v3
Get-CimInstance -ClassName Win32_UserProfile |
select LocalPath, SID, LastUseTime
C:\Users\Richard S-1-5-21-2542198769-1191... 01/06/2012 19:56:28
C:\Windows\ServiceProfil... S-1-5-20
C:\Windows\ServiceProfil... S-1-5-19
C:\Windows\system32\conf... S-1-5-18
Notice that with the CIM cmdlet we don’t have to perform any date conversions – worth switching just for that alone.
But the data above doesn’t show the user account.
Unfortunately there isn’t an association between profile and user account so we need to do the filtering ourselves
Get-WmiObject -Class Win32_UserProfile |
select LocalPath, SID,
@{N="LastUseTime"; E={$_.ConvertToDateTime($_.LastUseTime)}},
@{N="User"; E={Get-WmiObject -Class Win32_UserAccount -Filter "SID = '$($_.SID)'" | select -ExpandProperty Caption}}
LocalPath SID LastUseTime User
--------- --- ----------- ----
C:\Users\Richard S-1-5-21-25421987... 01/06/2012 20:01:56 RSLAPTOP01\Richard
C:\Windows\Servic... S-1-5-20
C:\Windows\Servic... S-1-5-19
C:\Windows\system... S-1-5-18
The alternative with the CIM cmdlets
Get-CimInstance -ClassName Win32_UserProfile |
select LocalPath, SID, LastUseTime,
@{N="User"; E={Get-CimInstance -Class Win32_UserAccount -Filter "SID = '$($_.SID)'" |
select -ExpandProperty Caption}}
C:\Users\Richard S-1-5-21-25421987... 01/06/2012 20:01:56 RSLAPTOP01\Richard
C:\Windows\Servic... S-1-5-20
C:\Windows\Servic... S-1-5-19
C:\Windows\system... S-1-5-18
The final part is to filter out any of the well known special accounts such as Local service
Get-WmiObject -Class Win32_UserProfile -Filter "Special = '$false'" |
select LocalPath, SID,
@{N="LastUseTime"; E={$_.ConvertToDateTime($_.LastUseTime)}},
@{N="User"; E={Get-WmiObject -Class Win32_UserAccount -Filter "SID = '$($_.SID)'" | select -ExpandProperty Caption}}
or
Get-CimInstance -ClassName Win32_UserProfile -Filter "Special = '$false'" |
select LocalPath, SID, LastUseTime,
@{N="User"; E={Get-CimInstance -Class Win32_UserAccount -Filter "SID = '$($_.SID)'" | select -ExpandProperty Caption}}
either of these will just return the top line in the output above.
Now we can identify our profiles & relate them to user accounts – how do we delete them