Skip to content

Commit 993fc6b

Browse files
committed
Added Remove-OldFiles function
1 parent 20b93b5 commit 993fc6b

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

Tests/WindowsDiskCleanup.Tests.ps1

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
Import-Module .\WindowsDiskCleanup\WindowsDiskCleanup.psm1 -Force
2+
3+
Describe 'WindowsDiskCleanup.Tests' {
4+
Context 'Remove-OldFiles Tests' {
5+
BeforeAll {
6+
$path = "$PSScriptRoot\test.txt"
7+
}
8+
9+
BeforeEach {
10+
$file = New-Item -Path $path -ItemType File -Force
11+
$file.CreationTimeUtc = (Get-Date).AddDays(-10)
12+
}
13+
14+
AfterEach {
15+
if (Test-Path $path) {
16+
Remove-Item -Path $path -Force
17+
}
18+
}
19+
20+
It 'should remove old file by Path (parameter)' {
21+
Remove-OldFiles -Path $file.FullName -Days 5 -DryRun:$false
22+
Test-Path $path | Should -Be $false
23+
}
24+
25+
It 'should remove old file by Path (pipeline)' {
26+
$file.FullName | Remove-OldFiles -Days 5 -DryRun:$false
27+
Test-Path $path | Should -Be $false
28+
}
29+
30+
It 'should remove old file by File (parameter)' {
31+
Remove-OldFiles -File $file -Days 5 -DryRun:$false
32+
Test-Path $path | Should -Be $false
33+
}
34+
35+
It 'should remove old file by File (pipeline)' {
36+
$file | Remove-OldFiles -Days 5 -DryRun:$false
37+
Test-Path $path | Should -Be $false
38+
}
39+
40+
It 'should not remove files in dry run mode' {
41+
Remove-OldFiles -File $file -Days 5 -DryRun:$true
42+
Test-Path $path | Should -Be $true
43+
}
44+
45+
It 'should not remove files that are not old enough' {
46+
$file.CreationTimeUtc = (Get-Date).AddDays(-3)
47+
Remove-OldFiles -File $file -Days 5 -DryRun:$false
48+
Test-Path $path | Should -Be $true
49+
}
50+
}
51+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
function Remove-OldFiles {
2+
[CmdletBinding()]
3+
param(
4+
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "File")]
5+
[System.IO.FileSystemInfo]$File,
6+
7+
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = "Path")]
8+
[string]$Path,
9+
10+
[Parameter(Mandatory = $true)]
11+
[int]$Days,
12+
13+
[switch]$DryRun
14+
)
15+
16+
begin {
17+
$now = Get-Date
18+
}
19+
20+
process {
21+
if ($PSCmdlet.ParameterSetName -eq 'Path') {
22+
$File = Get-Item -Path $Path
23+
}
24+
25+
if (($now - $File.CreationTimeUtc).TotalDays -gt $Days) {
26+
if ($DryRun) {
27+
Write-Host "[Dry] Removing $($File.FullName)" -ForegroundColor Yellow
28+
}
29+
else {
30+
Remove-Item -Path $File.FullName -Force
31+
}
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)