Search code examples
windowspowershellscriptinguser-profile

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
#$numberOfDays

$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?

Solution

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

      $(Get-Date).Date.AddDays($null)
      
    2. Are you sure there are profiles that match that data? Check the data when $numberOfDays is null to confirm.