-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCleanup_All_Files_in_All_SubFolders.sql
60 lines (55 loc) · 1.99 KB
/
Cleanup_All_Files_in_All_SubFolders.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Delete files older than 48 hours
$CleanUpTimeHours = 48
$CleanUpTimeMinutes = 5
$a = Get-ChildItem I:\Backups\CW | Where-Object {$_.Name -like '*BKS*'}
$filesRemoved = @();
try {
if($a.Count -gt 0)
{
foreach($x in $a)
{
$y = ((Get-Date) - $x.CreationTime);
$y_Hours = ($y.Days * 24) + ($y.Hours);
$y_Minutes = ($y.Days * 24) + ($y.Hours) + ($y.Minutes);
#Folder
if ($y_Hours -gt $CleanUpTimeHours -and $x.PsISContainer)
{
Write-Output "Removing folder '$($x.Name)' with its content";
$files = Get-ChildItem $x.Fullname -Recurse | Where-Object {$_.PsISContainer -ne $True};
$subFolders = Get-ChildItem $x.Fullname -Recurse | Where-Object {$_.PsISContainer};
# If files are found, then delete them
if($files) {
$filesNames = $files | Select-Object -ExpandProperty Name;
$files | Remove-Item;
}
# If sub-folders are found, then delete them
if($subFolders) {
$subFolders | Remove-Item;
}
$filesRemoved += $filesNames;
$x.Delete();
}
}
}
if($filesRemoved.Count -eq 0) {
Write-Output "No files to remove";
}
else {
Write-Output "`r`nBelow files were removed successfully:- ";
Write-Output $filesRemoved;
}
return 0; #success
}
catch {
$formatstring = "{0} : {1}`n{2}`n" +
" + CategoryInfo : {3}`n" +
" + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
$_.ErrorDetails.Message,
$_.InvocationInfo.PositionMessage,
$_.CategoryInfo.ToString(),
$_.FullyQualifiedErrorId
$formatstring -f $fields
Write-Output ($_.Exception.Message);
return 1; #failure
}