Question:
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 :
1 2 3 4 5 |
\\\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.
1 2 3 4 5 6 |
$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 ?
Answer:
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:
1 2 3 4 5 6 |
$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:
1 2 3 |
$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:
1 2 |
Get-ChildItem \\myserver\test\User\Profiles\*\AppData\Roaming\Microsoft\Windows\Cookies | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue |