Delete files recursively with PowerShell

I need to delete all files (recursively in all folders and subfolders) depending on the time of the last access .

I watched a Stack Overflow batch file to delete files older than N days that suggested this answer:

forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path" 

However, this deletes the files based on the last modified time, not the last access time.

Also, is there a way to save the command in a script file so that I can just double-click it to run?

+4
source share
2 answers

Use Get-ChildItem -recurse to get all the files, then you can pass them to the where-object command line to filter directories and use the LastAccessTime property to filter based on this attribute. Then you pass the result to the foreach object, which executes the delete command.

The result is as follows. Note the use of Get-Date to update all files from the beginning of the year, replace with your own date:

 get-childitem C:\what\ever -recurse | where-object {-not $_.PSIsContainer -and ($_.LastAccessTime -gt (get-date "1/1/2012"))} | foreach-object { del $_ } 

Or use some common aliases to shorten everything:

 dir C:\what\ever -recurse | ? {-not $_.PSIsContainer -and ($_.LastAccessTime -gt (get-date "1/1/2012"))} | % { del $_ } 
+7
source

As an aside, so you would do the same (get files only) in PowerShell 3.0:

 $old = Get-Date "1/1/2012" Get-ChildItem C:\what\ever -File -Recurse | Where-Object {$_.LastAccessTime -gt $old} | Remove-Item -Force 
+4
source

Source: https://habr.com/ru/post/1433673/


All Articles