Long story short, I have a customer who is trying to figure out why logs are filling up their server. That's not really something I need to worry about, other than I need to continually go through and clear out logs from a ton of servers so my application can run. I'm trying to figure out a script that will clear out the log folder. Ideally, this should work:
Get-ChildItem -Path $filePath -Include *.* -Recurse | foreach { $_.Delete()}
but some of the files are still in use, so I'm getting this:
Exception calling "Delete" with "0" argument(s): "The process cannot access the file
'filename' because it is being used by another process."
At line:1 char:87
... $filePath -Include *.* -Recurse | foreach { $_.Delete()}
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : IOException
Is there something I can add to this to ignore files that are still in use?
CodePudding user response:
If you're not interested in keeping log of what files where deleted and which files were in use you can simply pipe Get-ChildItem to Remove-Item and use -ErrorAction SilentlyContinue (-EA 0 for short) to suppress the error messages.
Note the use of -File is easier and more efficient than -Include *.*.
You can also add -Force for Remove-Item:
Forces the cmdlet to remove items that cannot otherwise be changed, such as hidden or read-only files or read-only aliases or variables.
Get-ChildItem -Path $filepath -File -Recurse -EA 0 | Remove-Item -Confirm:$false -EA 0
