Good afternoon. I have been through many iterations of the script below:
`
$Path = "C:\Users"
$ExcludedUsers = "Default", "Public", "Administrator"
$Targetdate = (get-date).AddDays(-30)
$UserFolders = $Path | Get-ChildItem -Directory -Exclude $ExcludedUsers |where-object {$_.LastWriteTime -lt ($targetdate)} | select-object Name
#gets computer space before cleanup
$before = get-volume -driveletter c | select-object SizeRemaining
#DELETETHEPROFILES
foreach($User in $userFolders)
{ get-ciminstance -classname win32_userprofile -Property LocalPath | Where-object ($_.LocalPath -like '*$User.Name') | remove-ciminstance -whatif
}
#gets computer space after cleanup
$after = get-volume -driveletter c | select-object SizeRemaining
#calculates space freed
$freed = ($before.SizeRemaining - $after.SizeRemaining)*(0.000000001)
`
$userfolders pulls a list of usernames and I'm trying to use that list to run remove-ciminstance to delete the profiles etc.
$_.LocalPath is in format "c:\users\username" I'm trying to point it to each profile in the $userFolders variable.
Now it runs great if i replace Where-object ($.LocalPath -like '*$User.Name') with Where-Object ($.LocalPath -like 'an actual username from the $Userfolders variable). Deleted the profile and life's great, but the minute i replace that with the foreach part *$User.Name it doesn't delete folder and doesn't throw an error, just does nothing.
I'm pretty sure i'm not using proper syntax and that's why i get a problem with the *$User.Name, but not sure what i should be using.
I just can't get the syntax right to find each username in a variable and delete it.