How to delete old profiles with script

Solution 1:

Basically, the mistake is in this line:

$UserProfile = Get-WmiObject win32_userprofile | Where localpath -EQ c:\\users\\$file

$UserProfile is null, and will always be null, because the equality comparer -eq is looking for an exact match, to put it into perspective:

'C:\some\path' -eq 'C:\\some\\path' # => False

[pscustomobject]@{
    localPath = 'C:\some\path'
} | Where-Object localPath -EQ 'C:\\some\\path' # => Null

To fix this, you can do the following:

# $UserAccountPath = "C:\\Users\\$file" // This line is not needed
#
# DirectoryInfo objects have a FullName property for their Absolute Path
$UserProfile = Get-WmiObject win32_userprofile | Where-Object localpath -EQ $file.FullName
Remove-WmiObject -InputObject $UserProfile

$UserProfile = Get-WmiObject win32_userprofile | Where-Object localpath -EQ $file.FullName
$UserProfile.Delete()