Suppressing confirmation on Remove-Item WITHOUT using -recurse - powershell

So I want to delete top level directories based on creation date. I don't want my script to consider ANY dates below that (e.g. my top level folder might be 31 days old, whereas subdirectories may be newer - but I still want the whole top level directory removed along with everything in it - I only care about the top level folder's creation date. Thus I don't want to use -recurse. However, I keep getting prompted with the whole "the folder has subdirectories do you want to continue...blah blah". Can't have that. How can I suppress this without using -recurse? I've tried Remove-Item -Force -confirm:$false as well as Remove-Item -Force -ea 0 to no avail. (PS -ea 0 is short for -ErrorAction SilentlyContinue) Thanks!
Get-ChildItem -Path e:\myfolder -Force | Where-Object { $_.PSIsContainer -and $_.CreationTime -lt (Get-Date).AddDays(-29) } | Remove-Item -Force

Related

Delete folder with content exclude folder with content

I need to write a script that deletes folders with last write time ~7 Days. But keep 2 "special" folder with the content in it.
Here's my script so far:
$source = "D:\TestOrdner"
$time = (Get-Date)#.AddDays(-7)
Start-Transcript "C:\log_files\log.txt"
gci $source -Recurse | ?{$_.LastWriteTime -lt $time} | del -Force -Verbose
Stop-Transcript
My only problem is how to EXCLUDE the folders with content?
My folder to keep: D:\TestOrdner\Test.
Be careful when deleting user profile folders, so keep the -WhatIf switch until you are absolutely sure the below will not delete folders that should not be deleted.
It might be a good idea to Move these folders instead of deleting them?
Since this concerns a user profile folder where every user has his/her own folder directly under the root folder, there is no need for the -Recurse switch on Get-ChildItem
Anyhow, this should do it:
$source = "D:\TestOrdner"
$time = (Get-Date).AddDays(-7)
Start-Transcript "C:\log_files\log.txt"
Get-ChildItem $source -Directory -Exclude 'Administrator','Default','Public' |
Where-Object {$_.LastWriteTime -lt $time} |
Remove-Item -Recurse -Force -confirm:$false -WhatIf
Stop-Transcript

How do I remove a Folder in Powershell?

we got a small script that creates folders named by the daily date. I got a script that deletes folders which are older than 30 days.
dir "\\nas\Backup_old\*" -ErrorAction SilentlyContinue |
Where { ((Get-Date) - $_.LastWriteTime).days -gt 30} |
Get-ChildItem -Recurse | Remove-Item -Recurse -Force
Principally it works fine. The Subfolders with contend will be deleted.
But the main folder is still existing and the LastWriteTime is canged to the runtime of the script. The folder is empty. Someone have a idea to solve this problem?
You probably just need to remove the second instance of Get-ChildItem (noting that dir is just an alias for Get-ChildItem), as that is causing it to remove the children of each of the directories returned by the first:
Get-ChildItem "\\nas\Backup_old\*" -ErrorAction SilentlyContinue |
Where-Object { ((Get-Date) - $_.LastWriteTime).days -gt 30} |
Remove-Item -Recurse -Force -WhatIf
Have a look at the WhatIf output and if it looks like it will now remove what you expect, remove -WhatIf.

Delete parent directory if file is present with appropriate timestamp

Using PowerShell I'd like to search a directory tree which will have a subset of folders. If a file called NOW is present within those folders and is 3 days old I'd like to delete the parent directory.
I think I have the search syntax right, then piping to a foreach loop but I can't figure out how to remove the parent directory.
Get-ChildItem -Path C:\tools\test1 -Filter NOW -Recurse |
foreach ($_) ???
Any help would be much appreciated, thanks
Get-ChildItem returns System.IO.FileInfo objects for files. One of the properties is Directory. So what you would be wanting to remove the directory. The Directory is still and object and we need the full path from it.
Remove-Item $_.Directory.FullName -Force -Recurse
The above would remove the folder, where NOW resides, and its contents. But you have another condition for age. Couple of ways to do this but one would be to use New-TimeSpan to compare the creation time to Now. Using the Days property of the TimeSPam
(New-TimeSpan -start $_.CreationTime -end ([datetime]::Now)).Days -gt 3
Putting that together with what you already have. -File will ensure we dont get folder matches.
$refdate = (Get-Date).Date.AddDays(-3)
Get-ChildItem -Path "C:\tools\test1" -Filter "NOW" -Recurse -File |
Where-Object{$_.CreationTime -gt $refdate} |
ForEach-Object{ Remove-Item $_.Directory.FullName -Force -Recurse -WhatIf }
The -WhatIf will help you identify the folders this process would attempt to remove. If you dont have at least PowerShell version 3 you could do this.
$refdate = (Get-Date).Date.AddDays(-3)
Get-ChildItem -Path "C:\tools\test1" -Filter "NOW" -Recurse |
Where-Object{(!$_.PSIsContainer) -and ($_.CreationTime -gt $refdate)} |
ForEach-Object{ Remove-Item $_.Directory.FullName -Force -Recurse -WhatIf }

How to keep a specific folder and delete rest of the files using powershell

I am trying delete all files within a folder but there is 1 folder called pictures which I would like to keep but don't know how to do that. I am using the following script , it deletes everything in a folder
if ($message -eq 'y')
{
get-childitem "C:\test" -recurse | % {
remove-item $_.FullName -recurse
}
}
One solution is to use something like:
Get-ChildItem -Path "c:\test" -Recurse | Where-Object { $_.FullName -cnotmatch "\\Pictures($|\\)" -and (Get-ChildItem $_.FullName -Include "Pictures" -Recurse).Length -eq 0 } | Remove-Item -Recurse -ErrorAction SilentlyContinue;
I suspect there must be a way more elegant way to do this. Here's what this does: it enumerates all files in the C:\test folder recursively (Get-ChildItem), then it removes all items from the result list using Where-Object where the path contains the directory to be excluded (specified using regex syntax) or when the item in question has child items that contains the file or directory to be excluded. The resulting list is fed to Remove-Item for removal. The -ErrorAction SilentlyContinue switch is applied to prevent errors being logged with recursive removal.
Get-ChildItem $PSScriptRoot -Force| Where-Object {$_.Name -ne "Pictures"} | Remove-Item -Recurse
I just tried this, and it worked for me. If you want to change what is deleted just change the "Pictures". This uses $PSScriptRoot for the path, which is the execution path of the Powershell script. You can rename that to be the path of where you want to delete.

Searching and deleting registry entries using wildcards

Is it possible to search for a wildcard - example *WAAgent* or *WAHost* and delete every registry key that references that wildcard statement above?
You may try something like:
Get-ChildItem -Path HKLM:\ -Recurse -Include *WAAgent* -ErrorAction SilentlyContinue | Remove-Item
Get-ChildItem -Path HKLM:\ -Recurse -Include *WAHost* -ErrorAction SilentlyContinue | Remove-Item
You have to specify in -Path if they are location in HKLM(local machine) or HKCU(current user), as they are two different drives. This has to be run as admin, and will give lots of errors(that's why I used -ErrorAction SilentlyContinue to hide them).
CAUTION: Personally I don't think it's smart to be using wildcards in registry though since it may delete something you didn't know about that could crash the system. My recommendation would be to compile a list of paths to the keys you want to remove and loop through it with foreach to delete one by one. Again, wildcards are DANGEROUS in registry.
If you are searching for a property value instead of a key value (and delete the relative key) you can use something like this:
gci HKLM: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath)
-match "WAAGent") { $_.PsPath} } | Remove-Item
Like for the #Graimer's answer, BE CAREFULL!!!
As all have already suggested, use this with extremely caution!! The following will go through all registry hives. Keep in mind that a matching key found can have a deep structure underneath it and you're deleting it all. Remove the WhatIf switch to actually delete the keys.
Get-ChildItem Microsoft.PowerShell.Core\Registry:: -Include *WAAgent*,*WAHost* -Recurse |
Remove-Item -Recurse -Force -WhatIf
I had the problem that there was a Session ID in the path of the registry.
To solve this is got the first part of the registry, stored it in a variable and used this for my foreach loop where the keys for drive mappings were stored.
The above was too rigorous in my case.
The below shows an example to remove (local) drive mappings in a session (the problem i had).
Start-Sleep -Seconds 20
# This stores the Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\SessionInfo\<SESSIONID>"
$SessionInfo = Get-Item "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\SessionInfo\*"
cd "HKCU:\"
Start-Sleep -Seconds 1
$Items = Get-ChildItem "$SessionInfo\MyComputer\Namespace"
foreach($Item in $Items){
Remove-Item $Item -Force -Recurse -Verbose
}