Delete folder with content exclude folder with content - powershell

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

Related

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.

powershell copy all folder structure and exclude one or more folders

I'm trying to use PowerShell to copy a folder with sub-folders from our users to a small backup. These folders contain a folder called "windows" I don't want to copy.
I have tried "exclude" but can't seem to get it to work.
This is the script so far:
Copy-Item "E:\Curos folder" -Exclude 'Windows' -Destination "E:\Curos folder backup" -Recurse -Verbose
I have read other posts but don't quiet understand how it works
It's my first time working with PowerShell
You are complete right.
Actually the script it's simpler than the one I have wrote before.
Here we go:
$source = "C:\Users\gaston.gonzalez\Documents\02_Scripts"
$destination = "D:\To Delete"
$exclude = "Windows"
$folders = Get-ChildItem -Path $source | Where {($_.PSIsContainer) -and ($exclude -notcontains $_.Name)}
foreach ($f in $folders){
Write-Host "This folders will be copied: $f"
Copy-Item -Path $source\$f -Destination $destination\$f -Recurse -Force
}
I'd use something like this:
Get-ChildItem $root -Directory -Recurse | % {$_.name -ne 'Windows'} | foreach {Copy-Item "$($_.FullName)" -Destination $dest -Recurse}
I haven't tested it but it's the skeleton of something you should be able to make work, although I don't find the point of using recurse on both, Get-ChildItem and Copy-Item my advice is to use it on Get-ChildItem.

Deleting specific folders within folders that have changing names

So my boss needs me to create a script that deletes everything in a directory with the exception of the folders with the name "incoming" and "outgoing," while still deleting all files and directories within those folders. These two folders are also stored in random company name folders so I cant specify each one as the list will keep growing.
How can I delete all the incoming and outgoing folder contents without deleting the folder that those folders are stored in?
Here is the code I have so far:
Get-ChildItem -Path ("C:\Users\testuser\Desktop\Test") -Exclude "Incoming","Outgoing" | foreach ($_) {
"CLEANING :" + $_.FullName
Remove-Item $_.FullName -Force -Recurse
"CLEANED... :" + $_.FullName
}
Is this the right approach? is there a switch or something that I should be adding to this command to add extra options? This script will be run daily via a Windows task I'm going to setup. Maybe there's a way to specify how deep the deletion script goes?
Hopefully this is what you need. This should delete files and folders that are in under the folders "Incoming" and "Outgoing."
$folders = Get-ChildItem -Path "C:\Users\mkrouse\Desktop\Test" -Recurse -Directory | Where-Object {($_.basename -contains "Incoming") -or ($_.BaseName -contains "Outgoing")}
foreach($folder in $folders){
$items = Get-ChildItem -Path $folder.FullName -Recurse
foreach($file in $items) {
Remove-Item -Path $file.FullName -Recurse -Force -WhatIf
}
}

Recursively remove desktop.ini files

I'm trying to delete all of the desktop.ini files in a given directory; namely Documents\Gio. I've tried del /S desktop.ini and del /S *.ini in cmd (admin mode) and get-childitem .\ -include desktop.ini -recurse | foreach ($_) {remove-item $_.fullname} and get-childitem .\ -include *.ini -recurse | foreach ($_) {remove-item $_.fullname} in PowerShell (also admin). Neither have worked. What should I do?
The desktop.ini files contain the following:
[.ShellClassInfo]
InfoTip=This folder is shared online.
IconFile=C:\Program Files\Google\Drive\googledrivesync.exe
IconIndex=12
I move the directory from my Google Drive folder but all the folders still have the shared icons on them. I was trying to change the directory and all it subdirectories and files' ownership to a different account. I tried to do this with Google Drive but only the root directory changed ownership; I can't delete any of the files or directories therein.
del /s /a desktop.ini
See del /? for help.
I had a similar problem and here is my solution:
Get-Location | Get-ChildItem -Force -Recurse -File -Filter "desktop.ini" | Remove-Item
The first part gets the current active directory.
Get-Location
You could replace it with a path like:
"C:\Users\Chris" | Get-ChildItem -Force -Recurse -File -Filter "desktop.ini" | Remove-Item
The second part gets child items in the path.
Get-ChildItem -Force -Recurse -File -Filter "desktop.ini"
-Force -> force seeing all child items even hidden ones, most "desktop.ini" are hidden
-Recurse -> to be recursive
-File -> to get only files else it could find a folder named "desktop.ini"
-Filter "desktop.ini" -> to only get items named "desktop.ini"
The last part removes the item.
Remove-Item
Adding a -WhatIf for the first run may be safer.
Remove-Item -WhatIf
This is what I used for Windows 2012 server
Create Desktop.ini files
My desktop.ini files were created from running this script which sets default folder options
$key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced'
Set-ItemProperty $key Hidden 1
Set-ItemProperty $key HideFileExt 0
Set-ItemProperty $key ShowSuperHidden 1
Stop-Process -processname explorer
Remove Desktop.ini files
# Remove from your user desktop
gci "$env:USERPROFILE\Desktop" -filter desktop.ini -force | foreach ($_) {remove-item $_.fullname -force}
# Remove from default desktop
gci "C:\Users\Public\Desktop" -filter desktop.ini -force | foreach ($_) {remove-item $_.fullname -force}
This will grab every folder in your home directory, and then search that folder for desktop.ini and delete it. It should be faster than using -recurse because it won't search subfolders. It should finish neatly with no errors
foreach ($file in Get-ChildItem -path \\server\homedrivedirectory) {
Get-ChildItem $file.FullName -Filter desktop.ini -force | remove-item -force -WhatIf
}
This will grab every folder in your home directory, and then create a path for every folder to \server\homedrivedirectory\user\desktop.ini and then delete that file. It should run a little faster as it doesn't have to search each user folder but it will turn up errors for every user folder that doesn't have a desktop.ini
foreach ($_ in Get-ChildItem -path \\server\homedrivedirectory) {
$path = $_.fullname
Remove-Item "$path\desktop.ini" -Force -WhatIf
}
I've left a -whatif so you can see what it would do in your environment without it doing it. If you want it to actually delete the files remove the -whatif
With powershell, you use the Get-ChildItem (alias gci) cmdlet to retrieve all desktop.ini files and pipe it to Remove-Item (alias rm):
gci 'C:\YOURPATHTODOCUMENTS\GO' -Filter desktop.ini -Recurse | rm

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 }