Skip to content

Instantly share code, notes, and snippets.

@jhochwald
Last active January 20, 2019 20:11
Show Gist options
  • Save jhochwald/beac6115b826ca51002c2be68f55f22e to your computer and use it in GitHub Desktop.
Save jhochwald/beac6115b826ca51002c2be68f55f22e to your computer and use it in GitHub Desktop.
#region Info
<#
#################################################
# modified by : Joerg Hochwald
# last modified : 2016-05-28
#################################################
Support: https://github.com/jhochwald/NETX/issues
#>
#endregion Info
#region License
<#
Copyright (c) 2012-2016, NET-Experts <http:/www.net-experts.net>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
By using the Software, you agree to the License, Terms and Conditions above!
#>
#endregion License
function global:Remove-TempFiles {
<#
.SYNOPSIS
Removes all temp files older then a given time period
.DESCRIPTION
Removes all temp files older then a given time period from the system or the user environment.
.PARAMETER Month
Remove temp files older then X month.
The default is 1
.PARAMETER Context
Remove the System or User Temp Files?
The default is All.
.EXAMPLE
PS C:\> Remove-TempFiles -Confirm:$false
TotalSize Retrieved TotalSizeMB RetrievedMB
--------- --------- ----------- -----------
518485778 417617315 494,5 398,3
Description
-----------
Removes all 'User' and 'System' temp file older then one month,
without asking if you are sure! This could be dangerous...
.EXAMPLE
PS C:\> Remove-TempFiles -Confirm:$false
WARNING: The process cannot access the file 'C:\Users\josh\AppData\Local\Temp\FXSAPIDebugLogFile.txt' because it is being used by another process. - Line Number: 96
TotalSize Retrieved TotalSizeMB RetrievedMB
--------- --------- ----------- -----------
264147489 214105710 251,9 204,2
Description
-----------
Removes all 'User' and 'System' temp file older then one month,
without asking if you are sure! This could be dangerous...
One file is locked by another process! Just a warning will show up,
the cleanup will continue.
.EXAMPLE
PS C:\> Remove-TempFiles -Month 3 -Context 'System'
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y")
TotalSize Retrieved TotalSizeMB RetrievedMB
--------- --------- ----------- -----------
264147489 214105710 251,9 204,2
Description
-----------
Removes all 'System' temp files older then 3 month
.EXAMPLE
PS C:\> Remove-TempFiles -Month 3 -Context 'User'
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y")
TotalSize Retrieved TotalSizeMB RetrievedMB
--------- --------- ----------- -----------
151519609 145693231 144,5 138,9
Description
-----------
Removes all 'User' temp files older then 3 month.
.NOTES
Adopted from a snippet found on Powershell.com
.LINK
Source http://powershell.com/cs/blogs/tips/archive/2016/05/27/cleaning-week-deleting-temp-files.aspx
#>
[CmdletBinding(ConfirmImpact = 'High',
SupportsShouldProcess = $true)]
[OutputType([System.Object])]
param
(
[Parameter(Position = 1,
HelpMessage = 'Remove temp files older then X month.')]
[System.Int64]$Month = 1,
[Parameter(ValueFromPipeline = $true,
Position = 2,
HelpMessage = 'Remove the System or User Temp Files?')]
[ValidateSet('System', 'User', 'All', IgnoreCase = $true)]
[System.String]$Context = 'All'
)
#requires -Version 3
#Requires -RunAsAdministrator
BEGIN {
# Look at temp files older than given period
$cutoff = ((Get-Date).AddMonths(- $Month))
# Use an ordered hash table to store logging info
$sizes = [Ordered]@{ }
}
PROCESS {
if ($Context -eq 'System') {
$Target = "$env:windir\temp"
} elseif ($Context -eq 'User') {
$Target = "$env:temp"
} elseif ($Context -eq 'All') {
$Target = "$env:windir\temp", $env:temp
} else {
Write-Error -Message "I have no idea what to clean: $($Target)" -ErrorAction:Stop
# Still here? Make sure we are done!
break
# Aw Snap! We are still here? Fix that the hard way...
exit 1
}
if ($pscmdlet.ShouldProcess("$($Context)", "Remove Temp file older then $($Month)")) {
<#
Mind the Pipes. All in a very long command :-)
#>
# Find all files in both temp folders recursively
Get-ChildItem $Target -Recurse -Force -File |
# calculate total size before cleanup
ForEach-Object {
$sizes['TotalSize'] += $_.Length
$_
} |
# take only outdated files
Where-Object { $_.LastWriteTime -lt $cutoff } |
# Try to delete. Add retrieved file size only if the file could be deleted
ForEach-Object {
try {
$fileSize = $_.Length
Remove-Item -Path $_.FullName -Force -Confirm:$false -ErrorAction Stop -WarningAction SilentlyContinue
$sizes['Retrieved'] += $fileSize
} catch [System.Exception] {
Write-Warning "$($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)"
} catch {
# Did not see this one coming!
Write-Warning "Unable to remove $($_.FullName)"
}
}
}
}
END {
# Turn bytes into MB
$Sizes['TotalSizeMB'] = [Math]::Round(($Sizes['TotalSize']/1MB), 1)
$Sizes['RetrievedMB'] = [Math]::Round(($Sizes['Retrieved']/1MB), 1)
# Dump the info
New-Object -TypeName PSObject -Property $sizes
}
}
@jhochwald
Copy link
Author

Update: Better Examples!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment