PowerShell command fails after variable is used


I’m trying to run a command to gather use profiles with certain requirements, here’s my code:

#$numberOfDays = 30

$profileStructsToRemove = Get-CimInstance Win32_UserProfile | 
    Where-Object {$_.LastUseTime -lt $(Get-Date).Date.AddDays(-$numberOfDays) } |
    Where-Object {$_.LocalPath.ToUpper() -ne 'C:\USERS\ADMINISTRATOR'} |
    Where-Object {$_.LocalPath.ToUpper() -ne 'C:\USERS\SOME_PROFILE_TO_KEEP'} |
    Where-Object {$_.LocalPath.ToUpper() -ne 'C:\USERS\PUBLIC'}

$profileStructsToRemove #print

I use the $numberOfDays variable to determine the number of days subtracted from today’s date that I want to use as the filter. Right now it’s commented out, and the command succeeds, although since $numberOfDays isn’t defined I assume it’s using a null value? I’m not really sure but it works that way…

However, when I assign $numberOfDays to 30, it fails to populate the variable $profileStructsToRemove with ANYTHING at all. It just utterly fails. I could really use some input on why this is happenening.

  1. How is the command working when $numberOfDays isn’t defined? Is it just a null value, or treating it as 0 for the AddDays function?
  2. Why is this command failing once $numberOfDays is assigned a value?


  1. Yes, it’s null, which added zero days. This is fine – you can test with:

  2. Are you sure there are profiles that match that data? Check the data when $numberOfDays is null to confirm.

Answered By – G42

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published