go me thinking about the temp folder. Its one of those areas tucked away in your profile that just seems to get left to grow. Time to do something about it.
$testdate = (Get-Date).AddDays(-10) $names = "FXSAPIDebugLogFile.txt", "hsperfdata_Richard" ## assume TMP = TEMP $path = $env:TEMP Get-ChildItem -Path $path -File | where LastWriteTime -lt $testdate | where Name -NotIn $names | Remove-Item -Force #-WhatIf Get-ChildItem -Path $path -Directory | where LastWriteTime -lt $testdate | where Name -NotIn $names | Remove-Item -Force -Recurse #-WhatIf
I decide to use some of the new functionality in PowerShell v3 and separate the file and folder processing so I could play (er experiment) with some of the new parameters in Get-ChildItem
Get-ChildItem [-Attributes <FileAttributes]>] [-Directory] [-File] [-Force] [-Hidden] [-ReadOnly] [-System]
These are a separate parameter set which means that -exclude and –include don’t work with them.
So start by creating a date to test against. Anything older than this will be deleted. Define a few names of things that have to be left alone (these will probably be different on your system) and set the path. I’ve assumed that the TEMP and TMP environmental variables point to the same path. if your system is different put the rest of the code into a foreach loop to iterate through the two variables.
Starting with files we get all the files in the root of TEMP. The –File parameter means we only look at files – folders are automatically excluded.
I’ve then used two where statements. Now the obvious comment is that I could combine them but if I do that I have to check each file for its age and then if its name is in my exclusion list. This way I test for age and immediately filter out any file that it is too young. Then I test for name. Doing it this way gives a small performance increase if you have a lot of young files.
I then pass the files to Remove-Item to delete.
The directories are processed in a similar manner except that we use –Directory on Get-ChildItem and add –Recurse to the Remove-Item call so that non-empty folders are removed.
Next move is to make this a scheduled task using the new PowerShell scheduled task cmdlets.