Search code examples
powershellwmi

Script not assigning WMI objects to array correctly


I am trying to create a script that detects domain user profiles that are up to 15 days old and removes them. This will be bundled in a job that will log out any idle sessions before it runs.

I am aware that this would normally be done via GPO, however it is not fit for purpose for this particular business area for various reasons.

Here is my code:

#Assign how old the user profile must be for deletion
[int]$NoOfDays = 15

#Get WMI object where it is a domain account and over 15 days old
$Objects = @(Get-WmiObject -Class Win32_UserProfile | Where {
    (!$_.Special) -and
    $_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-15)
})

if ($Objects -eq $null) {
    #If no users returned, write to host.
    Write-Host "no profiles found for deletion"
} else {
    #If users are found, do the following
    foreach ($Object in $Objects) {
        Write-Host "'$($object.LocalPath)' has been identified for deletion"
    }

    foreach ($Object in $Objects) {
        try {
            Write-Host "Attempting to delete profile '$($Object.LocalPath)'"
            Remove-WmiObject
            Write-Host "Deleted profile '$($Object.LocalPath)' successfully."
        } catch {
            Write-Host "Unable to delete profile '$($Object.LocalPath)'" -ErrorAction Continue
        }
    }
}

There is no output, it just returns to command line with no error straight away.

I have attempted commenting out the bit that removes the profile, ending the else after the first for each statement to see what is identified for deletion however it has not worked.


Solution

  • $Objects = @(...) ensures that $Objects is an array, even if the command doesn't return a result. An array (even an empty array) never equals $null, so your first condition is never triggered.

    Change

    if ($Objects -eq $null) {
    

    to

    if ($Objects.Count -gt 0) {
    

    and the code should do what you expect.