Fardin Barashi
Fardin Barashi

Reputation: 54

Remove accounts if lastusetime is older then value

enter image description hereIam trying to create a task that will executed later with tasksch on the local machine, that will run everyday.

The task is, if a user has not logged in to the computer, it shall be removed from the computer.

The Thing is there is something wrong with my code and i dont know what For now iam trying that the script shall remove testuser 1,2,3 and on testuser 4 is shall say Account is not old by using lastusetime.

System-info

OS Name: Microsoft Windows 10 Enterprise OS Version: 10.0.17763 N/A Build 17763

Account-Info

@{Sid=S-1-5-21-3824012622-276487612-2647460976-1105; LocalPath=C:\Users\testuser4; LastUseTime=2019-05-13 19:27:57}

@{Sid=S-1-5-21-3824012622-276487612-2647460976-1109; LocalPath=C:\Users\testuser3; LastUseTime=2019-05-10 14:54:07}

@{Sid=S-1-5-21-3824012622-276487612-2647460976-1108; LocalPath=C:\Users\testuser2; LastUseTime=2019-05-10 14:54:07}

@{Sid=S-1-5-21-3824012622-276487612-2647460976-1107; LocalPath=C:\Users\testuser1; LastUseTime=2019-05-10 13:49:16}

# Start PS-Code
 $DeleteIfLastUseTimetIsOlderThen = (get-date).AddDays(-5).tostring("yyyy-MM-dd hh:mm:ss”) 

 $GetLocalAccounts = Get-WmiObject -ComputerName localhost -Filter "Special=False" -Class Win32_UserProfile | 
 Select-Object Sid, LocalPath, @{Label='LastUseTime';Expression={$_.ConvertToDateTime($_.LastUseTime)} }  

  foreach ($UserAccount in $GetLocalAccounts) 
   { 
    if ($GetLocalAccounts.LastUseTime -Ge $DeleteIfLastUseTimetIsOlderThen )  
     { Write-host "Account is old, Remove me"}
      Else 
       { Write-host "Account is not old"}
 } 
# End PS-Code

The thing is that it doesn't matter if I change the value "$DeleteIfLastUseTimetIsOlderThen " to 1,2,3,4 or 55, everything seems to be old.

Upvotes: 0

Views: 400

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

The issue here is twofold. One is that you want to use a less than comparison when looking for an older date since a date in the past is less than a date in the future. Second, you want to compare each date in your collection ($GetLocalAccounts) with a specific fixed date ($DeleteIfLastUseTimeIsOlderThan). To do this with your code structure, you will need to check against the current object ($UserAccount) in your for loop.

# Start PS-Code
 $DeleteIfLastUseTimetIsOlderThan = (get-date).AddDays(-5).tostring("yyyy-MM-dd hh:mm:ss”) 

 $GetLocalAccounts = Get-WmiObject -ComputerName localhost -Filter "Special=False" -Class Win32_UserProfile | 
 Select-Object Sid, LocalPath, @{Label='LastUseTime';Expression={$_.ConvertToDateTime($_.LastUseTime)} }  

  foreach ($UserAccount in $GetLocalAccounts) 
   { 
    if ($UserAccount.LastUseTime -le $DeleteIfLastUseTimetIsOlderThan )  
     { Write-host "Account is old, Remove me"}
      Else 
       { Write-host "Account is not old"}
 } 
# End PS-Code

Upvotes: 1

Related Questions