0

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.

  • [https://adamtheautomator.com/powershell-delete-user-profile/](https://adamtheautomator.com/powershell-delete-user-profile/) – Olaf Dec 22 '22 at 19:09
  • Also https://stackoverflow.com/questions/43472546/how-to-remove-user-profiles-with-powershell – Jeff Zeitlin Dec 22 '22 at 19:12
  • -like '*$User.Name' Try switching to "double-quotes". 'Single-quotes' are for string literals, your variable won't get expanded. – Grok42 Dec 22 '22 at 19:48
  • 2
    @Grok42 as far as powershell syntax goes, you must use double-quotes **and** evaluation `$( )` to get a property from a variable like: `"*$($user.name)"`, otherwise the `.name` part doesn't get expanded. And like the other comments suggest - there are better ways to delete user profiles – Cpt.Whale Dec 22 '22 at 19:56
  • To add to @Cpt.Whale's comment: The linked duplicates deal with the primary problems: the first one explains why `'$foo'` cannot work (no string interpolation inside `'...'`); the second one explains why `"$foo.bar"` won't work as intended (requires `"$($foo.bar)"`). There's at least one other problem with your code: your second `Where-object` call uses `(...)` instead of `{ ... }`. If there are any remaining questions, please create a _new_ question post. – mklement0 Dec 22 '22 at 22:35

0 Answers0