I'm new to PowerShell and I have been trying create a script but so far, I have been unsuccessful. I want it to do a specific task which is ;
I need to be able to search through a drive for a specific folder called "Cookies"
and delete it. The problem only is the folder cookies is set at multiple locations.
Example :
\\\myserver\test\User\Profiles\USER1\AppData\Roaming\Microsoft\Windows\Cookies
\\\myserver\test\User\Profiles\USER2\AppData\Roaming\Microsoft\Windows\Cookies
\\\myserver\test\User\Profiles\USER3\AppData\Roaming\Microsoft\Windows\Cookies
\\\myserver\test\User\Profiles\USER4\AppData\Roaming\Microsoft\Windows\Cookies
and go on...
How do I get powershell to go trough all those different USER folder to search for the Cookies folder and delete it.
I came up with this, but I was hoping a powershell guru could help me.
$cookies= Get-ChildItem \\myserver\test\User\Profiles\*\AppData\Roaming\Microsoft\Windows\Cookies
foreach ($cookie in $cookies){
Remove-Item "$cookies" -Force -Recurse -ErrorAction SilentlyContinue
}
Will this work ?
You are almost there. No need to use quotes around $cookies
.
If you do a foreach ($cookie in $cookies)
, then operate on $cookie
in the script block, not $cookies
.
This works:
$cookies = Get-ChildItem \\myserver\test\User\Profiles\*\AppData\Roaming\Microsoft\Windows\Cookies
foreach ($cookie in $cookies){
Remove-Item $cookie -Force -Recurse -ErrorAction SilentlyContinue
}
but this will work as well, without a loop:
$cookies = Get-ChildItem \\myserver\test\User\Profiles\*\AppData\Roaming\Microsoft\Windows\Cookies
Remove-Item $cookies -Force -Recurse -ErrorAction SilentlyContinue
If you want a one-liner and no variables:
Get-ChildItem \\myserver\test\User\Profiles\*\AppData\Roaming\Microsoft\Windows\Cookies | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
Try this one liner -
$path = "\\myserver\test\User\Profiles\"
Get-ChildItem $path -Recurse -Directory | Where-Object {$_.Name -eq 'Cookies'} | % {Remove-Item $_.FullName}
This is a little bit simplified version. Just for the sake of safety I would run it first with -WhatIf
to verify if the result is correct. Then just comment the other line
$path = ""
$pattern = ""
Get-ChildItem $path -recurse -directory -include $pattern |
Remove-Item -WhatIf
#Remove-Item -Force -ErrorAction SilentlyContinue
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.