Get-ChildItem ignoring "$Recycle.bin" folder? - powershell

I've started using a powershell script to clean all files that are older than 30 days in the roaming profiles of all our users.
This is the script I use:
$oldTime = [int]30 #30 days
foreach ($path in Get-Content "pathList.txt") {
Write-Host "Trying to delete files older than $oldTime days, in the folder $path" -ForegroundColor Green
Get-ChildItem $path -Recurse -Verbose | WHERE {($_.CreationTime -le $(Get-Date).AddDays(-$oldTime))} | Remove-Item -Recurse -Force
}
Here is the Pathlist.txt
\\FS001\RDS_FolderRedirection$\*\Downloads
\\FS001\RDS_FolderRedirection$\*\Downloads\$RECYCLE.BIN
For some reason the script ignores the $RECYCLE.BIN folder.. am I missing something here?

Try the -Force param with Get-ChildItem, the Documentation explains it's use as:
Allows the cmdlet to get items that cannot otherwise not be accessed by the user, such as hidden or system files.
It would be used in your code like this:
Get-ChildItem $path -Recurse -Verbose -Force

Related

Iterate files recursively

I have a powershell script that iterates files from a certain network directory. In this directory, there are aroud 190 sub directories, each containing several files.
I use this to perform the job:
get-childitem -Path $pathFilesOrig -Recurse -Force -Include *.pdf, *.csv | ForEach {
write-host "INFO:File name: $_"
}
However, it does not loop in certain directories, whereas there are valid files in it and access rights are fine (I can access those files through windows explorer manually).
I have tried the following to check if I can at least iterate every directory:
get-childitem -Path $pathFilesOrig -Recurse -Force | ?{ $_.PSIsContainer } | ForEach {
write-host "INFO:Dir name: $_"
}
When I do it, the script displays every directory.
Now I do it to list files in each directory:
get-childitem -Path $pathFilesOrig -Recurse -Force | ?{ $_.PSIsContainer } | ForEach {
write-host "INFO:Dir name: $_"
$tmpDirName = $pathFilesOrig + $_.Name
get-childitem -Path $tmpDirName | ForEach {
Write-Host "INFO:File name: $_"
And in this case, again, some directories are missing.
There is not even the result of the second line write-host "INFO:Dir name: $_" which was working fine previously.
I don't understand, and I am certainly missing something...
Thanks for your help.
I suspect your problem has to do with the -Include parameter which filters items after the provider has collected all of the objects versus -Filter which handles it at enumeration, i.e., when it's getting the objects first. You can further improve performance by only enumerating files using the -File parameter.
#requires -Version 3
Get-ChildItem -Path $pathFilesOrig -Filter *.pdf, *.csv -File -Force -Recurse
If this command fails to resolve your problem, I suspect you actually do have a privileges problem since -Force will get hidden directories, but does not supersede access.

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

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.

Windows PowerShell - Delete Files Older than X Days

I am currently new at PowerShell and I have created a script based on gathered information on the net that will perform a Delete Operation for found files within a folder that have their LastWriteTime less than 1 day.
Currently the script is as follows:
$timeLimit = (Get-Date).AddDays(-1)
$oldBackups = Get-ChildItem -Path $dest -Recurse -Force -Filter "backup_cap_*" |
Where-Object {$_.PSIsContainer -and $_.LastWriteTime -lt $timeLimit}
foreach($backup in $oldBackups)
{
Remove-Item $dest\$backup -Recurse -Force -WhatIf
}
As far as I know the -WhatIf command will output to the console what the command "should" do in real-life scenarios. The problem is that -WhatIf does not output anything and even if I remove it the files are not getting deleted as expected.
The server is Windows 2012 R2 and the command is being runned within PowerShell ISE V3.
When the command will work it will be "translated" into a task that will run each night after another task has finished backing up some stuff.
I did it in the pipe
Get-ChildItem C:\temp | ? { $_.PSIsContainer -and $_.LastWriteTime -lt $timeLimit } | Remove-Item -WhatIf
This worked for me. So you don't have to ttake care of the right path to the file.
other solution
$timeLimit = (Get-Date).AddDays(-1)
Get-ChildItem C:\temp2 -Directory | where LastWriteTime -lt $timeLimit | Remove-Item -Force -Recurse
The original issue was $dest\$backup would assume that each file was in the root folder. But by using the fullname property on $backup, you don't need to statically define the directory.
One other note is that Remove-Item takes arrays of strings, so you also could get rid of the foreach
Here's the fix to your script, without using the pipeline. Note that since I used the where method this requires at least version 4
$timeLimit = (Get-Date).AddDays(-1)
$Backups = Get-ChildItem -Path $dest -Directory -Recurse -Force -Filter "backup_cap_*"
$oldBackups = $backups.where{$_.LastWriteTime -lt $timeLimit}
Remove-Item $oldBackups.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