Ryan
Ryan

Reputation: 11

Deleting a folder out of all user directories

I'm trying to delete a folder out of the \AppData\Local\Microsoft_Corporation directory for all users on a given computer. I found a few PowerShell script that can complete this task for me but extra wrinkle here is that this folder name is slightly different for every user. The folder name I'm trying to remove looks like this - harmony_Path_lzm5ceganmb1ihkqq2. It always has the word "harmony" in the folder name, so I'm trying to search for any folder with this keyword and remove it.

This is the script I have so far:

$users = Get-ChildItem C:\Users
foreach ($user in $users){
   $folder = "$($user.fullname)\AppData\Local\Microsoft_Corporation\*"
     If (Test-Path $folder) {
          Remove-Item $folder -Recurse -Force -ErrorAction silentlycontinue -WhatIf
     }
}

This seems to work fine to remove every folder in \AppData\Local\Microsoft_Corporation\ but when I try to search for "harmony" keywords with the Where-Object Cmdlet. I can't get it to work correctly.

$users = Get-ChildItem C:\Users
foreach ($user in $users){
   $folder = "$($user.fullname)\AppData\Local\Microsoft_Corporation\* | Where-Object {$_.Name -like "*harm*"}"
   If (Test-Path $folder) {
        Remove-Item $folder -Recurse -Force -ErrorAction silentlycontinue -WhatIf
   }
}

Can anyone help me with this?

Upvotes: 1

Views: 3080

Answers (2)

M.Pinto
M.Pinto

Reputation: 56

why did you put where-object inside " " ? powershell read this as a string

try using this:

$users = Get-ChildItem C:\Users
foreach ($user in $users){
   $folder = "$($user.fullname)\AppData\Local\Microsoft_Corporation\"
   If (Test-Path $folder) {
   Get-ChildItem $folder -Recurse | Where-Object {$_.Name -like "*harm*"}|Remove-Item -Force -ErrorAction silentlycontinue
   }
}

Upvotes: 0

Vincent K
Vincent K

Reputation: 1346

$users = Get-ChildItem C:\Users
foreach ($user in $users){
   $folder = "$($user.fullname)\AppData\Local\Microsoft_Corporation\*Harmony*"
     If (Test-Path $folder) {
          Remove-Item $folder -Recurse -Force -ErrorAction silentlycontinue -WhatIf
     }
}

$folder contains a string - path. It does not contains list of files to use Where-Object Cmdlet.

Another way:

Get-ChildItem "C:\Users\*\AppData\Local\Microsoft_Corporation\*harmony*" -Directory | Remove-Item -WhatIf

Upvotes: 2

Related Questions