-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfunctions.ps1
1625 lines (1321 loc) · 37.5 KB
/
functions.ps1
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.DESCRIPTION
Powershell General Functions
Functions to be used by anothers scripts
File especially created to be used by the script NTFS-HARDLINK-BACKUP
.NOTES
Author : Juan Antonio Tubio <[email protected]>
GitHub : https://github.com/jatubio
Date : 2015/04/09
Version : 1.1
#>
#To include only 1 time
$included_functions=$True
Function ShowArray
{
<#
.Synopsis
Show array contents formated.
.Description
Write the content of an array in a formated way.
Can output to screen, to a file and return one string.
To be used on debug and show info to the user
.Notes
Author : Juan Antonio Tubio <[email protected]>
GitHub : https://github.com/jatubio
Date : 2015/04/07
Version : 1.0
.Parameter arraytoshow
Specifies the Array or System.Collections.Hashtable to loop
.Parameter filename
Specifies the path to the output file.
.Parameter showName
Instead of show item, show only .Name property
.Parameter showLength
Show the length of array
.Parameter writeHost
Also write messages to host.
.Outputs
String with the content of array in a formated way.
.Example
ShowArray $lastBackupFolders "lastBackupFolders.txt" -showName
-----------
Loop $lastBackupFolders and write all item.Name on "lastBackupFolders.txt" file
.Example
$echo=ShowArray $lastBackupFolders -writeHost
-----------
Loop $lastBackupFolders and write all items on host console and return also to
$echo variable
#>
[CmdletBinding()]
Param(
[AllowEmptyCollection()]
[Parameter(Mandatory=$True)]
[array]$arraytoshow,
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$False)]
[string]$filename,
[Parameter(Mandatory=$False)]
[switch]$showName=$False,
[Parameter(Mandatory=$False)]
[switch]$showLength=$False,
[Parameter(Mandatory=$False)]
[switch]$writeHost=$False
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing"
$summary=""
if($writeHost -eq $True) {Write-Host ""}
foreach($item in $arraytoshow)
{
if($showName -eq $True) {
$echo=$item.Name
} else {
$echo=$item.ToString()
}
if($writeHost -eq $True) {Write-Host $echo}
$summary+="$echo`n"
}
if($showLength -eq $True)
{
$echo=("`nTotal Items: " + ($arraytoshow.length))
$summary+=$echo
if($writeHost -eq $True) {Write-Host $echo}
}
if($filename) { echo $summary > $filename }
return "`n"+$summary
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing"
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
Function GetFolderDate
{
<#
.Synopsis
Returns The DateTime of a Folder Backup
.Description
Gets the name of a folder backup and returns its DateTime
.Notes
Author : Juan Antonio Tubio <[email protected]>
GitHub : https://github.com/jatubio
Date : 2015/04/07
Version : 1.0
.Parameter foldername
Specifies the folder name with format "Name - YYYY-MM-DD HH-MM-SS"
.Outputs
DateTime
.Example
GetFolderDate $folderName
-----------
Returns DateTime of folder in the format set on windows
.Example
GetFolderDate "Test Folder - 2014-08-11 10-18-20"
-----------
Returns DateTime of folder (08/11/2014 10:18:20)
#>
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[string]$folderName
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing"
# Format Name of folder on a correct DateTime Format replacing "-" with ":" in the TimeStamp
$folderDate=(($folderName.Substring($folderName.length - 19 , 11)) + ( $folderName.Substring($folderName.length - 8) -replace "-",":" ))
$folderDate=(Get-Date $folderDate)
return $folderDate
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing"
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
Function GetTimeSpanFolders
{
<#
.Synopsis
Returns an HashTable with the backup folders to keep for a time span
.Description
Get the max number of folders to keep and the time span for each item and
Returns an HashTable with the backup folders to keep for a time span
.Notes
Author : Juan Antonio Tubio <[email protected]>
GitHub : https://github.com/jatubio
Date : 2015/04/07
Version : 1.0
.Parameter folders
One array of backup folders names (Sorted from most recent to older)
.Parameter every
Time span for each item. (In days by default)
.Parameter maxItems
Max number of items to keep
.Parameter format
Format of every ("minutes","hours","days","months" or "years")
Default to days.
.Parameter fixedTime
If fixedTime, we use last time span date to calculate next 'time span'
to next backup item. Default to False
Else, we use last keeped backup item date.
.Parameter minutes
Take every parameter as minutes
.Parameter hours
Take every parameter as hours
.Parameter days
Take every parameter as days
.Parameter months
Take every parameter as months
.Parameter years
Take every parameter as years
.Outputs
lastBackupsToKeep Hash
.Example
$DailyFolders=GetTimeSpanFolders $lastBackupFolders 10 4 -hours
-----------
Returns Hash of folders to keep with a backup each 10 hours and maximum 4 folders to keep
.Example
$AnnuallyFolders=GetTimeSpanFolders $lastBackupFolders 6 10 -months
-----------
Returns Hash of folders to keep with a backup each 6 months and maximum 10 folders to keep
#>
[CmdletBinding()]
Param(
[AllowEmptyCollection()]
[Parameter(Mandatory=$True)]
[Array]$folders,
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[Int32]$every,
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[Int32]$maxItems,
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$False)]
[string]$format="days",
[Parameter(Mandatory=$False)]
[switch]$fixedTime,
[Parameter(Mandatory=$False)]
[switch]$minutes,
[Parameter(Mandatory=$False)]
[switch]$hours,
[Parameter(Mandatory=$False)]
[switch]$days,
[Parameter(Mandatory=$False)]
[switch]$months,
[Parameter(Mandatory=$False)]
[switch]$years
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing"
$lastBackupsToKeep=@()
if($years) {
$format="years"
} elseif($months) {
$format="months"
} elseif($days) {
$format="days"
} elseif($hours) {
$format="hours"
} elseif($minutes) {
$format="minutes"
}
#Write-Host("`nKeeping $maxItems backups, each every $every ($format)") # &&&
# Let's calculate dates back
$every=$every * -1
$spanDateTime=AddDateTime $(Get-Date -f "yyyy-MM-dd HH:mm:ss") $every $format
#Write-Host "Start datetime: $($spanDateTime)" # &&&
#Loop through each item checking if it's inside of span time
#From newest to farthest
foreach($folderName in $folders)
{
#Initialize variables
if (!(test-path variable:\lastDate)) {$lastDate = ""} # test for EXISTENCE & create
if (!(test-path variable:\lastFolder)) {$lastFolder = ""} # test for EXISTENCE & create
$folderDate=GetFolderDate $folderName
if($lastBackupsToKeep.length -lt $maxItems)
{
if($folderDate -lt $spanDateTime)
{
# When we get the first item out of range, we get the closest found between the last and current.
if($lastFolder)
{
#Write-Host("Difference between the last ($lastDate) it's " + ($lastDate - $spanDateTime)) # &&&
#Write-Host("Difference between the current ($folderDate) it's " + ($spanDateTime - $folderDate)) # &&&
# If the current is closer, we get them
if(($lastDate - $spanDateTime) -gt ($spanDateTime - $folderDate))
{
$lastBackupsToKeep+=$folderName
$lastDate=$folderDate
}
else
{
$lastBackupsToKeep+=$lastFolder #Else, we get the last
}
}
else
{
# If we haven't lastFolder, we get current
$lastBackupsToKeep+=$folderName
$lastDate=$folderDate
}
#Write-Host("Taken " + $lastBackupsToKeep[-1]) # &&&
#If fixed time, we add 'every' time span to last time span date
if($fixedTime -eq $True)
{
$spanDateTime=AddDateTime (Get-Date $spanDateTime) $every $format
}
else #Else, we add 'every' time span to last keeped item date
{
$spanDateTime=AddDateTime (Get-Date $lastDate) $every $format
}
#Write-Host("*(" + $lastBackupsToKeep.length +")* new datetime: " + ($spanDateTime) + "`n") # &&&
}
#If we have taken current, reset last to don't take them again
if($lastDate -eq $folderDate)
{
$lastFolder=""
$lastDate=""
}
else
{
$lastFolder=$folderName
$lastDate=$folderDate
}
}
else
{
break
}
}
return $lastBackupsToKeep
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing"
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
Function AddDateTime
{
#Auxiliar function used by GetTimeSpanFolders
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[DateTime]$time,
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[Int32]$every,
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[string]$format
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing"
if($format -eq "years") {
return ($time).AddYears($every)
} elseif($format -eq "months") {
return ($time).AddMonths($every)
} elseif($format -eq "days") {
return ($time).AddDays($every)
} elseif($format -eq "hours") {
return ($time).AddHours($every)
} elseif($format -eq "minutes") {
return ($time).AddMinutes($every)
}
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing"
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
Function DeleteFolder
{
<#
.Synopsis
Delete one backup folder
.Description
Delete one backup folder using ln.exe --deeppathdelete parameter
.Notes
Author : Juan Antonio Tubio <[email protected]>
GitHub : https://github.com/jatubio
Date : 2015/04/07
Version : 1.0
.Parameter foldername
Specifies the folder name to delete
.Outputs
Nothing
.Example
DeleteFolder $folderName
#>
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[string]$folderName
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing"
`cmd /c "`"`"$lnPath`" --deeppathdelete `"$folderName`" $logFileCommandAppend`""`
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing"
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
Function GetAllBackupsSourceItems
{
<#
.Synopsis
Get collection of backups items belonging source.
.Description
Extracted code from International-Nepal-Fellowship original version
Loop all folders on backup destination directory and filter by backup
source folder name
.Notes
Author : Juan Antonio Tubio <[email protected]>
GitHub : https://github.com/jatubio
Date : 2015/04/09
Version : 1.0
.Backwards Compatibility
International-Nepal-Fellowship original version work with folder items.
I have changed here to return only collection of names, no more folder items.
.Parameter BackupDestination
$selectedBackupDestination
.Parameter EscapedBackupSourceFolder
$backup_source_folder escaped
If not provided, it will take all folders "backup type"
.Outputs
Hashtable lastBackupFolders
.Example
$oldBackupFolders=@(GetAllBackupsSourceItems $selectedBackupDestination $backup_source_folder_escaped)
-----------
Gets all folders of backups belonging to $backup_source_folder_escaped in $selectedBackupDestination folder
.Example
$oldBackupFolders=@(GetAllBackupsSourceItems $selectedBackupDestination)
-----------
Gets all folders of 'backups type' in $selectedBackupDestination folder
#>
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[String]$BackupDestination,
[Parameter(Mandatory=$False)]
[ValidateNotNullOrEmpty()]
[String]$EscapedBackupSourceFolder
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing (BackupDestination=$BackupDestination)"
# Contains the list of folders inside backup destination folder
$oldBackupItems = Get-ChildItem -Force -Path $BackupDestination | Where-Object {$_ -is [IO.DirectoryInfo]} | Sort-Object -Property Name
# Contains the list of the backups belonging to source
$lastBackupFolders = @()
if(!$EscapedBackupSourceFolder)
{
$matchString = ''
}
else
{
$matchString = '^'+ $EscapedBackupSourceFolder
}
$matchString = $matchString + ' - (\d{4})-\d{2}-\d{2} \d{2}-\d{2}-\d{2}$'
foreach ($item in $oldBackupItems)
{
if ($item.Name -match $matchString ) {
$lastBackupFolders += $item.name
}
}
return $lastBackupFolders
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing"
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
Function DeleteBackupFolders
{
<#
.Synopsis
Delete a collection of Backup Folders.
.Description
If collection have no elements, show one message with
'No old backups were deleted'
.Notes
Author : Juan Antonio Tubio <[email protected]>
GitHub : https://github.com/jatubio
Date : 2015/04/10
Version : 1.1
.Parameter backupDestination
Path of backup destination folder
.Parameter backupsToDelete
Specifies the collection with backup folders to delete
.Parameter DryRun
Simulation Mode. Not do any writing on the hard disk, instead it
will just report the actions it would have taken.
.Outside Scope Variables
Reads Parameters $EchoVerbose,$LogVerbose
.Outputs
Nothing
.Example
DeleteBackupFolders $selectedBackupDestination $backupFolders
#>
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[String]$backupDestination,
[AllowEmptyCollection()]
[Parameter(Mandatory=$True)]
[Array]$backupsToDelete,
[Parameter(Mandatory=$False)]
[switch]$DryRun=$False
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing"
$log=""
if($backupsToDelete.length -gt 0)
{
if($DryRun -eq $True)
{
$echo="Simulation Mode: No backup folder(s) will be damaged :)"
$log+="`r`n$echo`r`n`r`n"
Write-Host "`n$echo`n"
}
elseif($Script:DryRun -eq $True)
{
$DryRun=$True
}
$echo=("Deleting " + $backupsToDelete.length + " old backup(s)`n")
if($DryRun -eq $True) {$echo="**Simulated** "+$echo}
if($EchoVerbose) { Write-Host $echo }
if($LogVerbose) { $log+="`r`n$echo" }
foreach($folder in $backupsToDelete)
{
$folderToDelete = $backupDestination +"\"+ $folder
$echo="Deleting $folderToDelete"
if($DryRun -eq $True) {$echo="**Simulated** "+$echo}
if($EchoVerbose) { Write-Host $echo }
if($LogVerbose) { $log+="`r`n$echo" }
if($DryRun -eq $False)
{
DeleteFolder "$folderToDelete"
}
}
$echo="Deleted " + $backupsToDelete.length +" old backup(s)`n"
if($DryRun -eq $True) {$echo="**Simulated** "+$echo}
Write-Host "`n$echo"
$log+="`r`n$echo"
}
else
{
$echo="No old backups were deleted"
#if($DryRun -eq $True) {$echo="**Simulated** "+$echo} ZZZ
Write-Host "`n$echo"
$log+="`r`n$echo"
}
WriteLog $log
$emailBody = $emailBody + $log
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing"
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
Function WriteLog
{
<#
.Synopsis
Write text in log file
.Description
.Notes
Author : Juan Antonio Tubio <[email protected]>
GitHub : https://github.com/jatubio
Date : 2015/04/10
Version : 1.0
.Parameter text
Specifies the text to write on log file
.Outputs
Nothing
.Outside Scope Variables
$LogFile
.Example
WriteLog "testing"
#>
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[string]$text
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing"
if ($LogFile) {
$text | Out-File "$LogFile" -encoding ASCII -append
}
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing"
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
Function DeleteLogFiles
{
<#
.Synopsis
Get a collection of folders names (or only with date-time strings) and delete
the log file belonging to them
.Description
If collection have no elements, show one message with
'No old logfiles were deleted'
.Notes
Author : Juan Antonio Tubio <[email protected]>
GitHub : https://github.com/jatubio
Date : 2015/04/10
Version : 1.0
.Parameter logFileDestination
Path of logs destination folder
.Parameter folderNames
Specifies the collection with backup folders to delete
.Parameter DryRun
Simulation Mode. Not do any writing on the hard disk, instead it
will just report the actions it would have taken.
.Outputs
Nothing
.Example
DeleteLogFiles $logFileDestination $backupsToDelete
.Example
DeleteLogFiles $logFileDestination $lastLogFiles
#>
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[String]$logFileDestination,
[AllowEmptyCollection()]
[Parameter(Mandatory=$True)]
[Array]$folderNames,
[Parameter(Mandatory=$False)]
[switch]$DryRun=$False
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing"
$log=""
if($DryRun -eq $True)
{
$echo="Simulation Mode: No backup folder(s) will be damaged :)"
$log+="`r`n$echo`r`n`r`n"
Write-Host "`n$echo`n"
}
elseif($Script:DryRun -eq $True)
{
$DryRun=$True
}
$echoDeleted=""
$logDeleted=""
$logFilesDeleted=0
if($folderNames.length -gt 0)
{
foreach($folder in $folderNames)
{
$logFileToDelete=$folder
#if it's a full backup name folder, get only date-time part.
if($logFileToDelete.length -gt 19)
{
$logFileToDelete=$logFileToDelete.Substring($logFileToDelete.length - 19)
}
$logFileToDelete = $logFileDestination +"\"+ $logFileToDelete + ".log"
$echo=""
If (Test-Path "$logFileToDelete")
{
$logFilesDeleted++
$echo="Deleting $logFileToDelete"
if($DryRun -eq $False)
{
Remove-Item "$logFileToDelete"
}
}
If (Test-Path "$logFileToDelete.zip")
{
$logFilesDeleted++
if($echo)
{
$echo+=" and (.zip)"
}
else
{
$echo="Deleting $logFileToDelete.zip"
}
if($DryRun -eq $False)
{
Remove-Item "$logFileToDelete.zip"
}
}
if($echo)
{
if($DryRun -eq $True) {$echo="**Simulated** "+$echo}
$logDeleted+="`r`n$echo"
$echoDeleted+="$echo`n"
}
}
}
if($logFilesDeleted -gt 0)
{
$echo=("Deleting " + $logFilesDeleted + " old log file(s)")
if($DryRun -eq $True) {$echo="**Simulated** "+$echo}
if($LogVerbose)
{
$log+="$echo`r`n"
$log+="`r`n$logDeleted"
}
if($EchoVerbose)
{
$echo+="`n`n$echoDeleted"
Write-Host "$echo"
}
$echo="Deleted " + $logFilesDeleted +" old log files(s)"
if($DryRun -eq $True) {$echo="**Simulated** "+$echo}
Write-Host "`n$echo"
$log+="`r`n$echo"
}
else
{
$echo="No old log files were deleted"
if($DryRun -eq $True) {$echo="**Simulated** "+$echo}
Write-Host "`n$echo"
$log+="`r`n$echo"
}
WriteLog $log
$emailBody = $emailBody + $log
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing"
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
Function GetAllLogsFiles
{
<#
.Synopsis
Get collection of log files on logFileDestination folder
.Description
.Notes
Author : Juan Antonio Tubio <[email protected]>
GitHub : https://github.com/jatubio
Date : 2015/04/10
Version : 1.0
.Backwards Compatibility
International-Nepal-Fellowship original version work with file items.
I have changed here to return only collection of names, no more file items.
.Parameter logFileDestination
Path of logs destination folder
.Outputs
Hashtable lastLogFiles
.Example
$lastLogFiles=GetAllLogsFiles $logFileDestination
#>
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[String]$logFileDestination
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing"
$lastLogFiles = @()
# Contains the list of files inside logs destination folder
If (Test-Path $logFileDestination -pathType container) {
$oldLogItems = Get-ChildItem -Force -Path $logFileDestination | Where-Object {$_ -is [IO.FileInfo]} | Sort-Object -Property Name
# get me the old logs if any
foreach ($item in $oldLogItems) {
if ($item.Name -match '^(\d{4}-\d{2}-\d{2} \d{2}-\d{2}-\d{2}).log(.zip)*$' ) {
$lastLogFiles += $matches[1]
}
}
}
return $lastLogFiles
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing"
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
Function GetOrphanLogFiles
{
<#
.Synopsis
Gets a collection of log files and check if exist his belonging backup folder
.Description
If we wan't delete log files of existing backup folders, can use
this function to filter logFilesToDelete Collection
.Notes
Author : Juan Antonio Tubio <[email protected]>
GitHub : https://github.com/jatubio
Date : 2015/04/11
Version : 1.0
.Parameter backupDestination
Path of backup destination folder
.Parameter logFilesToDelete
Specifies the collection with log files to delete
Can be only date and time or include also belonging
folder name.
.Outputs
Nothing
.Example
$logFilesToDelete = @(GetOrphanLogFiles $selectedBackupDestination $logFilesToDelete)
#>
[CmdletBinding()]
Param(
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$True)]
[String]$backupDestination,
[AllowEmptyCollection()]
[Parameter(Mandatory=$True)]
[Array]$logFilesToDelete
)
Begin
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing"
# Get all of backup folders
$backupFolders=@(GetAllBackupsSourceItems $backupDestination)
$orphanLogs=@()
# Loop logFilesToDelete and find for a belonging backup folder
foreach($logFile in $logFilesToDelete)
{
$beforeLength=$backupFolders.length
if($beforeLength -gt 0)
{
#if it's a full backup name folder, get only date-time part.
$logDateTime=$logFile
if($logDateTime.length -gt 19)
{
$logDateTime=$logDateTime.Substring($logDateTime.length - 19)
}
# We catch only the folders that are not matching the logfile date
$backupFolders=$backupFolders -notlike "* - $logDateTime"
# If not have excluded folders, don't exists backups belonging this logfile