forked from 7k2mpa/FileMaintenace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileMaintenance.ps1
1618 lines (1037 loc) · 53.9 KB
/
FileMaintenance.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
#Requires -Version 3.0
#If you want to use '-PreAction compress or archive' option in FileMaintenance.ps1, install WMF 5.0 or later, and place '#Requires -Version 5.0' insted of '#Requires -Version 3.0'
#If you want to use '-PreAction compress or archive' option with 7-Zip in FileMaintenance.ps1, do not need to replace.
<#
.SYNOPSIS
This script processes log files or temp files to delete, move, archive, etc.... with multiple methods.
CommonFunctions.ps1 is required.
You can process files in multiple folders with Wrapper.ps1
.DESCRIPTION
This script finds files and folders that match up to multiple criteria.
And processes the files and folders found with multiple methods with PreAction, Action and PostAction.
Methods are
-PreAction:
Create new files from files found.
Methods [AddTimeStamp (to file name)][Compress][Archive (to 1file)][Move (the) NewFile (created to new location)] are offered and can be used together.
Without specification -MoveNewFile option, place the file created in the same folder of the original file.
-Action:
Process files found to [Move][Copy][Delete][NullClear][KeepFilesCount] , folders found to [DeleteEmptyFolders]
-PostAction:
Process files found to [NullClear][Rename]
Finding criteria are [(Older than)-Days][-Size][-(FileName)RegularExpression][-Parent(Path)RegularExpression]
This script processes only 1 folder at once.
If you process multiple folders, can do with Wrapper.ps1
Output log to [Windows Event Log] or [Console] or [Text Log] and specify to suppress or to output individually.
This scrpit requires PowerShell 3.0 or later.
If you run the scripts on Windows Server 2008 or 2008R2, must install latest WMF.
This script can use cmdlet Compress-Archive for '-PreAction compress or archive option'.
But cmdlet Compress-Archive can not handle wild card characters bracket[] for destination path correctly, you should install 7-Zip. This script can use 7-Zip for compress or archive also.
If you want to specify '-PreAction compress or archive' option in FileMaintenance.ps1 without installing 7-Zip, install WMF 5.0 or later, and place '#Requires -Version 5.0' instead of '#Requires -Version 3.0'
If you can install 7-Zip for compress or archive, do not need to replace.
https://docs.microsoft.com/ja-jp/PowerShell/scripting/install/installing-windows-PowerShell?view=PowerShell-7#upgrading-existing-windows-PowerShell
.EXAMPLE
FileMaintenace.ps1 -TargetFolder C:\TEST -noLog2Console -verbose
Find files in C:\TEST and child folders recuresively.
All logs are not output at console.
You would confirm getting files to process.
.EXAMPLE
FileMaintenace.ps1 -TargetFolder C:\TEST -Action Delete
Delete files in C:\TEST and child folders recuresively.
.EXAMPLE
FileMaintenace.ps1 -TargetFolder C:\TEST -Action DeleteEmptyFolders
Delete empty folders in C:\TEST and child folders recuresively.
.EXAMPLE
FileMaintenace.ps1 -TargetFolder C:\TEST -Action Delete -noRecurse
Delete files only in C:\TEST non-recuresively.
.EXAMPLE
FileMaintenace.ps1 -TargetFolder C:\TEST -Action Copy -MoveToFolder C:\TEST1 -Size 10KB -continue
Copy files over than 10KByte to C:\TEST1 recuresively.
If no child folder exists in the destination, make a new folder.
If a same name file exists in the destination, skip copying and continue to process a next object.
.EXAMPLE
FileMaintenace.ps1 -TargetFolder C:\TEST -RegularExpression '^.*\.log$' -PreAction Compress,AddTimeStamp -Action NullClear -Days 10
Find files ending with '.log' and older 10days in C:\TEST recuresively.
Create new files compressed and added time stamp to file name from files found.
New files place in the same folder.
The files that are found dose not be deleted, but are cleared with null.
.EXAMPLE
FileMaintenace.ps1 -TargetFolder C:\TEST -RegularExpression '^.*\.log$' -PreAction Compress,MoveNewFile -Action Delete -MoveToFolder C:\TEST1 -OverRide -Days 10
Find files ending with '.log' and older 10days in C:\TEST recuresively.
Create new files compressed and move to C:\TEST1
If a same name file exists in the destination, override old one.
The original files are deleted.
.EXAMPLE
FileMaintenace.ps1 -TargetFolder C:\OLD\Log -RegularExpression '^.*\.log$' -Action Delete -ParentRegularExpression '\\OLD\\'
Find files ending with '.log' recuresively.
-ParentRegularExpresssion option is specified with regular expression, thus path's backslash\ is escaped with backslash\
Delete them with '\OLD\' in the rest of the path characters next to the -TargetFolder(C:\OLD\Log)'s strings.
At the sample blow, 'C:\OLD\Los' dose not match up to -ParentRegularExpression.
Thus 'C:\OLD\Log\IIS\Current\Infra.log' , 'C:\OLD\Log\Java\Current\Infra.log' and 'C:\OLD\Log\Infra.log' are not deleted.
C:\OLD\Log\IIS\Current\Infra.log
C:\OLD\Log\IIS\OLD\Infra.log
C:\OLD\Log\Java\Current\Infra.log
C:\OLD\Log\Java\OLD\Infra.log
C:\OLD\Log\Infra.log
.EXAMPLE
FileMaintenace.ps1 -TargetFolder C:\TEST -CommonConfigPath .\CommonConfig.ps1
Find files in C:\TEST and child folders recuresively.
With CommonCOnfig.ps1 setting, event log's IDs are specified.
.PARAMETER TargetFolder
Specify a folder of the target files or the folders placed.
Specification is required.
Can specify relative, absolute or UNC path format.
Relative path format must be starting with 'dot.'
Wild cards are not accepted shch as asterisk* question? bracket[]
If the path contains bracket[] , specify path literally and do not escape.
.PARAMETER PreAction
Specify methods to process files.
-PreAction option accept multiple arguments.
Separate arguments with comma,
None:Do nothing, and is default. If you want to test the action, specify -WhatIf or -Confirm option.
Compress:Create new files compressed from the original files.
AddTimeStamp:Create new files with file name added time stamp.
Archive:Create an archive file from files found. Specify archive file name with -ArchiveFileName option.
MoveNewFile:place new files in -MoveNewFolder path.
7z:Specify to use 7-Zip and make .7z(LZMA2) for compress or archive option.
7zZip:Specify to use 7-Zip and make .zip(Deflate) for compress or arvhice option.
.PARAMETER Action
Specify method to process files.
None:Do nothing, and is default. If you want to test the action, specify -WhatIf or -Confirm option.
Move:Move the files found to -MoveNewFolder path.
Delete:Delete the files.
Copy:Copy the files found and place in -MoveNewFolder path.
DeleteEmptyFolders:Delete empty folders.
KeepFilesCount:Delete old generation files untill number of files is equal to be specified.
NullClear:Clear the files found with null.
.PARAMETER PostAction
Specify method to process files.
None:Do nothing, and is default. If you want to test the action, specify -WhatIf or -Confirm option.
Rename:Rename the files found with -RenameToRegularExpression
NullClear:Clear the files with null.
.PARAMETER MoveToFolder
Specify a destination folder of the files found moved to.
Can specify relative, absolute or UNC path format.
Relative path format must be starting with 'dot.'
Wild cards are not accepted shch as asterisk* question? bracket[]
If the path contains bracket[] , specify path literally and do not escape.
.PARAMETER ArchiveFileName
Specify the file name of the archive file with -PreAction Archive option.
Specify it without extension.
Extension strings will be added automatically with archive method.
.PARAMETER 7zFolder
Specify a folder of 7-Zip installed.
[C:\Program Files\7-Zip] is default.
.PARAMETER Days
Specify how many days older than today to process files.
[0] day is default and, process all files.
.PARAMETER Size
Specify size of files to process.
[0] byte is default, and process all files.
Units of KB,MB,GB are accepted.
e.g. [-Size 10MB] is equal to [-Size 10*1024^6]
.PARAMETER RegularExpression
Specify regular expression to match up to processing files.
['.*'] is default, and process all files.
Argument must be quoted with sigle quote'
In PowerShell specification, capital and small letter are equal value but, are not (some version?)
.PARAMETER ParentRegularExpression
Specify regular expression to match up to processing path of the files excluding -TargetFolder.
['.*'] is default, and process all files.
Argument must be quoted with sigle quote'
In PowerShell specification, capital and small letter are equal value but, are not (some version?)
.PARAMETER RenameToRegularExpression
Specify regular expression for rename rule when specify -PostAction Rename.
Specify rename pattern for -RegularExpression
https://docs.microsoft.com/ja-jp/dotnet/standard/base-types/substitutions-in-regular-expressions
.PARAMETER Recurse
Specify to process the files or folders in the path recursively or non-recuresively.
[$TRUE(recuresively)] is default.
.PARAMETER NoRecurse
Specify if you want to find files non-recursively.
The option overrides -Recurse option.
.PARAMETER OverRide
Specify if you want to override same name files in the destination in moving or copying process.
If the file in the destination path is equal or newer than the file in the source path, do not override and skip to process with counting up a Warning.
[$FALSE (terminate with an Error and do not override)] is default.
.PARAMETER OverRideAsNormal
Specify if you want to exit with Normal return code when override same name files in the destination in moving or copying process.
[$FALSE (terminate with a Warning when override)] is default.
.PARAMETER OverRideForce
Specify if you want to override same name files in the destination in moving or copying process.
If the file in the destination path is equal or newer than the file in the source path, force to override with counting up a Warning.
[$FALSE (terminate with an Error and do not override)] is default.
.PARAMETER Continue
Specify if you want to skip the process when files exist in -MoveToFolder alredy in moving or copying process and to process remains.
If the script skips the process, processes remains and terminates with a Warning.
[$FALSE (terminate with an Error immediately and do not skip)] is default.
.PARAMETER ContinueAsNormal
Specify if you do not want to override a files and to want to continue processing and to exit with Normal return code.
If the script skips to process, exits successfully.
[$FALSE (terminate with an Error immediately and do not skip)] is default.
.PARAMETER NoneTargetAsWarning
Specify if you want to terminate with a Warning when no file exists in the folder.
[$FALSE (exit with Normal when no file exists in the folder)] is default.
.PARAMETER CompressedExtString
Specify file extention strings in specifing -PreAction Compress option.
[.zip] is default.
.PARAMETER TimeStampFormat
Specify time stamp format in specifing -PreAction AddTimeStamp option
[_yyyyMMdd_HHmmss] is default.
It is deffernt from -LogDateFormat option.
.PARAMETER KeepFiles
Specify how many newer files in the folder to keep with -Action KeepFileCount option.
[1] is default.
.PARAMETER CommonConfigPath
Specify common configuration file path in relative path format.
Only this parameter, you can specify the path with only relative path format.
With this parameter, you can specify same event id for utility scripts with common config file.
If you want to cancel using common config file specified in Param section of the script, specify this argument with NULL or empty string.
.PARAMETER Log2EventLog
Specify if you want to output log to Windows Event Log.
[$TRUE] is default.
.PARAMETER NoLog2EventLog
Specify if you want to suppress log to Windows Event Log.
Specification overrides -Log2EventLog
.PARAMETER ProviderName
Specify provider name of Windows Event Log.
[Infra] is default.
.PARAMETER EventLogLogName
Specify log name of Windows Event Log.
[Application] is default.
.PARAMETER Log2Console
Specify if you want to output log to PowerShell console.
[$TRUE] is default.
.PARAMETER NoLog2Console
Specify if you want to suppress log to PowerShell console.
Specification overrides -Log2Console
.PARAMETER Log2File
Specify if you want to output log to text log.
[$FALSE] is default.
.PARAMETER NoLog2File
Specify if you want to suppress log to PowerShell console.
Specification overrides -Log2File
.PARAMETER LogPath
Specify the path of text log file.
Can specify relative, absolute or UNC path format.
Relative path format must be starting with 'dot.'
Wild cards are not accepted shch as asterisk* question? bracket[]
If the path contains bracket[] , specify path literally and do not escape.
[$NULL] is default.
If the log file dose not exist, the script makes a new file.
If the log file exists, the script writes log additionally.
.PARAMETER LogDateFormat
Specicy time stamp format in the text log.
[yyyy-MM-dd-HH:mm:ss] is default.
.PARAMETER LogFileEncode
Specify the character encode in the log file.
[Default] is default and it works as ShiftJIS.
.PARAMETER NormalReturnCode
Specify Normal Return code.
[0] is default.
Must specify NormalReturnCode < WarningReturnCode < ErrorReturnCode < InternalErrorReturnCode
.PARAMETER WarningReturnCode
Specify Warning Return code.
[1] is default.
Must specify NormalReturnCode < WarningReturnCode < ErrorReturnCode < InternalErrorReturnCode
.PARAMETER ErrorReturnCode
Specify Error Return code.
[8] is default.
Must specify NormalReturnCode < WarningReturnCode < ErrorReturnCode < InternalErrorReturnCode
.PARAMETER InternalErrorReturnCode
Specify Internal Error Return code.
[16] is default.
Must specify NormalReturnCode < WarningReturnCode < ErrorReturnCode < InternalErrorReturnCode
.PARAMETER InfoEventID
Specify information event id in the log.
[1] is default.
.PARAMETER InfoLoopStartEventID
Specify start loop event id in the log.
[2] is default.
.PARAMETER InfoLoopEndEventID
Specify end loop event id in the log.
[3] is default.
.PARAMETER StartEventID
Specify start script id in the log.
[8] is default.
.PARAMETER EndEventID
Specify end script event id in the log.
[9] is default.
.PARAMETER WarningEventID
Specify Warning event id in the log.
[10] is default.
.PARAMETER SuccessEventID
Specify Successfully complete event id in the log.
[73] is default.
.PARAMETER InternalErrorEventID
Specify Internal Error event id in the log.
[99] is default.
.PARAMETER ErrorEventID
Specify Error event id in the log.
[100] is default.
.PARAMETER ErrorAsWarning
Specfy if you want to return WARNING exit code when the script terminate with an Error.
.PARAMETER WarningAsNormal
Specify if you want to return NORMAL exit code when the script terminate with a Warning.
.PARAMETER ExecutableUser
Specify the users who are allowed to execute the script in regular expression.
[.*] is default and all users are allowed to execute.
Parameter must be quoted with single quote'
Escape the back slash in the separetor of a domain name.
example [domain\\.*]
.NOTES
The origin of [Delete Empty Folders] function comes from Martin Pugh's Remove-EmptyFolders released under MIT License.
(https://github.com/martin9700/Remove-EmptyFolders)
See also LICENSE_Remove-EmptyFolders.txt File.
Copyright 2020 Masayuki Sudo
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
.LINK
https://github.com/7k2mpa/FileMaintenace
.OUTPUTS
System.Int. Return Code.
#>
#!!! start of definition !!!#
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = "High")]
Param(
[String]
[parameter(position = 0, mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, HelpMessage = 'Specify a folder to process (ex. D:\Logs) or Get-Help FileMaintenance.ps1')]
[ValidatePattern('^(\\\\|\.+\\|[c-zC-Z]:\\)(?!.*(\/|:|\?|`"|<|>|\||\*)).*$')][Alias("Path","LiteralPath","FullName" , "SourcePath")]$TargetFolder ,
#[String]$TargetFolder, #for Validation debug
[Array][parameter(position = 1)]
[ValidateSet("none" , "AddTimeStamp" , "Compress", "MoveNewFile" , "Archive" , "7z" , "7zZip")]$PreAction = 'none' ,
[String][parameter(position = 2)]
[ValidateSet("none" , "Move", "Copy", "Delete" , "DeleteEmptyFolders" , "NullClear" , "KeepFilesCount")]$Action = 'none' ,
[String][parameter(position = 3)]
[ValidateSet("none" , "NullClear" , "Rename")]$PostAction = 'none' ,
[String][parameter(position = 4)]
[ValidatePattern('^(\\\\|\.+\\|[c-zC-Z]:\\)(?!.*(\/|:|\?|`"|<|>|\||\*)).*$')][Alias("DestinationPath")]$MoveToFolder ,
#[String]$MoveToFolder, #for Validation debug
[String][ValidateNotNullOrEmpty()][ValidatePattern('^(?!.*(\/|:|\?|`"|<|>|\||\*)).*$')]$ArchiveFileName = "archive" ,
[Int][ValidateRange(0,2147483647)]$KeepFiles = 1 ,
[Int][ValidateRange(0,730000)]$Days = 0 ,
[Int64][ValidateRange(0,9223372036854775807)]$Size = 0 ,
#[Regex][Alias("Regex")]$RegularExpression = '^(.*)\.txt$' , #RenameRegex Sample
[Regex][Alias("Regex")]$RegularExpression = '.*' ,
[Regex][Alias("PathRegex")]$ParentRegularExpression = '.*' ,
[Regex][Alias("RenameRegex")]$RenameToRegularExpression = '$1.log' ,
[Boolean]$Recurse = $TRUE ,
[Switch]$NoRecurse ,
[Switch]$OverRide ,
[Switch]$OverRideAsNormal ,
[Switch]$OverRideForce ,
[Switch]$Continue ,
[Switch]$ContinueAsNormal ,
[Switch]$NoneTargetAsWarning ,
[String][ValidatePattern('^\.(?!.*(\/|:|\?|`"|<|>|\||\*)).*$')]$CompressedExtString = '.zip',
[String][ValidatePattern('^(\\\\|\.+\\|[c-zC-Z]:\\)(?!.*(\/|:|\?|`"|<|>|\||\*)).*$')]$7zFolder = 'C:\Program Files\7-Zip' ,
[String][ValidatePattern('^(?!.*(\\|\/|:|\?|`"|<|>|\|)).*$')]$TimeStampFormat = '_yyyyMMdd_HHmmss' ,
#[String][ValidatePattern('^(|\0|(\.+\\)(?!.*(\/|:|\?|`"|<|>|\||\*))).*$')]$CommonConfigPath = '.\CommonConfig.ps1' , #MUST specify with relative path format
[String][ValidatePattern('^(|\0|(\.+\\)(?!.*(\/|:|\?|`"|<|>|\||\*))).*$')]$CommonConfigPath = $NULL ,
[Boolean]$Log2EventLog = $TRUE ,
[Switch]$NoLog2EventLog ,
[String][ValidateNotNullOrEmpty()]$ProviderName = 'Infra' ,
[String][ValidateSet("Application")]$EventLogLogName = 'Application' ,
[Boolean]$Log2Console = $TRUE ,
[Switch]$NoLog2Console ,
[Boolean]$Log2File = $FALSE ,
[Switch]$NoLog2File ,
[String][ValidatePattern('^(\\\\|\.+\\|[c-zC-Z]:\\)(?!.*(\/|:|\?|`"|<|>|\||\*)).*$')]$LogPath ,
[String][ValidateNotNullOrEmpty()]$LogDateFormat = 'yyyy-MM-dd-HH:mm:ss' ,
[String][ValidateSet("Default", "UTF8" , "UTF7" , "UTF32" , "Unicode")]$LogFileEncode = 'Default' , #Default ShiftJIS
[Int][ValidateRange(0,2147483647)]$NormalReturnCode = 0 ,
[Int][ValidateRange(0,2147483647)]$WarningReturnCode = 1 ,
[Int][ValidateRange(0,2147483647)]$ErrorReturnCode = 8 ,
[Int][ValidateRange(0,2147483647)]$InternalErrorReturnCode = 16 ,
[Int][ValidateRange(1,65535)]$InfoEventID = 1 ,
[Int][ValidateRange(1,65535)]$InfoLoopStartEventID = 2 ,
[Int][ValidateRange(1,65535)]$InfoLoopEndEventID = 3 ,
[int][ValidateRange(1,65535)]$StartEventID = 8 ,
[int][ValidateRange(1,65535)]$EndEventID = 9 ,
[Int][ValidateRange(1,65535)]$WarningEventID = 10 ,
[Int][ValidateRange(1,65535)]$SuccessEventID = 73 ,
[Int][ValidateRange(1,65535)]$InternalErrorEventID = 99 ,
[Int][ValidateRange(1,65535)]$ErrorEventID = 100 ,
[Switch]$ErrorAsWarning ,
[Switch]$WarningAsNormal ,
[Regex]$ExecutableUser = '.*'
)
################# CommonFunctions.ps1 Load #######################
# If you want to place CommonFunctions.ps1 in differnt path, modify
Try {
."$PSScriptRoot\CommonFunctions.ps1"
IF ($LASTEXITCODE -eq 99) {
Exit 1
}
}
Catch [Exception] {
Write-Error "Fail to load CommonFunctions.ps1 Please verify existence of CommonFunctions.ps1 in the same folder."
Exit 1
}
#!!! end of definition !!!
################# functions #######################
function Test-LeafNotExists {
<#
.SYNOPSIS
Check the path specified that a file or folder dose NOT exist in the path.
.DESCRIPTION
Check the path specified that a file or folder dose NOT exist in the path, and return $TRUE or $FALSE
.INPUT
@Strings of File Path
.OUTPUT
@Boolean
.NOTE
Cases in the destination path....
1 file exists with -OverRide option ...$TRUE, $OverRideFlag = $TRUE(-OverRide prior to -Continue) remind Invoke-Action override file anytime
2 file exists with -Continue option ...$FALSE, $ContinueFlag = $TRUE
3 file exists without option ...finalize with $ErrorReturnCode, if $FroceEndLoop=$TRUE then $FALSE, $ForceFinalize=$TRUE
4 FOLDER exists with -OverRide option ...can not override, thus finalize with $ErrorReturnCode, if $FroceEndLoop=$TRUE then $FALSE, $ForceFinalize=$TRUE
5 FOLDER exists with -Continue option ...$FALSE, $ContinueFlag = $TRUE
6 FOLDER exists without option ...finalize with $ErrorReturnCode, if $FroceEndLoop=$TRUE then $FALSE, $ForceFinalize=$TRUE
7 nothing exists ...$TRUE
#>
[OutputType([Boolean])]
[CmdletBinding()]
Param(
[String][parameter(position = 0, mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias("CheckPath" , "FullName")]$Path ,
[Switch]$ForceEndLoop = $ForceEndLoop ,
[Switch]$OverRide = $OverRide ,
[Switch]$OverRideAsNormal = $OverRideAsNormal ,
[Switch]$OverRideForce = $OverRideForce ,
[Switch]$Continue = $Continue ,
[Switch]$ContinueAsNormal = $ContinueAsNormal ,
[int]$InfoEventID = $InfoEventID ,
[int]$WarningEventID = $WarningEventID ,
[int]$ErrorEventID = $ErrorEventID
)
begin {
}
process {
Write-Log -ID $InfoEventID -Type Information -Message "Check existence of [$($Path)]"
Do {
#Case 7
IF (-not(Test-Path -LiteralPath $Path)) {
Write-Log -ID $InfoEventID -Type Information -Message "File [$($Path)] dose not exist."
$noExistFlag = $TRUE
Break
}
IF (Test-Path -LiteralPath $Path -PathType Leaf) {
Write-Log -ID $WarningEventID -Type Warning -Message "Same name file [$($Path)] exists already."
} else {
Write-Log -ID $WarningEventID -Type Warning -Message "Same name folder [$($Path)] exists already."
}
#Case 1
IF (($OverRide) -and (Test-Path -LiteralPath $Path -PathType Leaf)) {
Write-Verbose "Destination LastWriteTime[$((Get-Item -LiteralPath $Path).LastWriteTime)] Size[$((Get-Item -LiteralPath $Path).Length)]"
Write-Verbose "Source LastWriteTime[$($Target.Object.LastWriteTime)] Size[$($Target.Object.Length)]"
IF (-not($OverRideForce) -and (Get-Item -LiteralPath $Path).LastWriteTime -ge $Target.Object.LastWriteTime ) {
Write-Log -ID $WarningEventID -Type Warning -Message "Last write time of [$($Path)] is equal or newer than [$($Target.Object.FullName)] , thus does no override."
$Script:WarningFlag = $TRUE
$noExistFlag = $FALSE
Break
}
$Script:OverRideFlag = $TRUE
$noExistFlag = $TRUE
IF ($OverRideAsNormal) {
Write-Log -ID $InfoEventID -Type Information -Message ("A same name file exists in the destination already, but specified -OverRideAsNormal[$($OverRideAsNormal)] option, " +
"thus overrides the file in the destination [$($Path)] and counts a warning event as NORMAL.")
} else {
Write-Log -ID $WarningEventID -Type Warning -Message ("A same name file exists in the destination already, but specified -OverRide[$($OverRide)] option, " +
"thus overrides the file in the destination [$($Path)]")
$Script:WarningFlag = $TRUE
}
Break
}
#Case 2,5
IF ($Continue) {
$Script:ContinueFlag = $TRUE
$noExistFlag = $FALSE
IF ($ContinueAsNormal) {
Write-Log -ID $InfoEventID -Type Information -Message "Specified -ContinueAsNormal[$($ContinueAsNormal)] option, continues to process objects and count a warning event as NORMAL."
} else {
Write-Log -ID $WarningEventID -Type Warning -Message "Specified -Continue[$($Continue)] option, continues to process objects."
$Script:WarningFlag = $TRUE
}
Break
}
#Case 3,4,6
Write-Log -ID $ErrorEventID -Type Error -Message "Same name object exists already, thus forces to terminate $($ShellName)"
IF ((-not($ForceEndLoop)) -and (-not($MYINVOCATION.ExpectingInput))) { ;# $MYInvocation.ExpectingInput = $TRUE means, script run in the pipeline
Finalize $ErrorReturnCode
} else {
$Script:ErrorFlag = $TRUE
$Script:ForceFinalize = $TRUE
$noExistFlag = $FALSE
Break
}
}
While ($FALSE)
Write-Output $noExistFlag
}
end {
}
}
filter ComplexFilter {
<#
.SYNOPSIS
@filter objects with criteria
.DESCRIPTION
last write date is older than $Days
(file|folder) name match up to $RegularExpression
file size is over than $Size
C:\TargetFolder :TargetFolder
C:\TargetFolder\A\B\C\target.txt :TargetObject
part of \A\B\C\ match up to $ParentRegularExpression
.INPUT
PSobject
.OUTPUT
PSobject passed the filter
#>
IF ($_.LastWriteTime -lt (Get-Date).AddDays(-$Days)) {
IF ($_.Name -match $RegularExpression) {
IF ($_.Length -ge $Size) {
IF (($_.FullName).Substring($TargetFolder.Length, ($_.FullName | Split-Path -Parent).Length - $TargetFolder.Length +1) -match $ParentRegularExpression)
{Write-Output $_}
}
}
}
}
function Get-Object {
<#
.SYNOPSIS
@find objects(files or folders) in the specified folder
.INPUT
System.String. Path of the folder to get objects
.OUTPUT
PSObject
#>
[OutputType([PSObject])]
[CmdletBinding()]
Param(
[String][parameter(position = 0, mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)][Alias("TargetFolder" , "FullName")]$Path ,
[String][parameter(position = 1, mandatory)][ValidateSet("File" , "Folder")]$filterType ,
[Switch]$Recurse = $Recurse ,
[String]$Action = $Action
)
begin {
}
process {
$parameter = @{
LiteralPath = $Path
Recurse = $Recurse
Include = '*'
File = ($filterType -eq 'File')
Directory = ($filterType -eq 'Folder')
}
$objects = @()
$objects = ForEach ($object in (Get-ChildItem @parameter | ComplexFilter)) {
[PSCustomObject]@{
Object = $object
Time = $object.LastWriteTime
Depth = ($object.FullName.Split("\\")).Count
}
}
<#
some $Action process Object in order, thus sort the objects
KeepFilesCount: by last write date
DeleteEmptyFolders: by depth of the file path hierarchy with counting separator in the path for deleteing the deepest folder at first
#>
Write-Output $(Switch -Regex ($Action) {
'^KeepFilesCount$' {$objects | Sort-Object -Property Time}
'^DeleteEmptyFolders$' {$objects | Sort-Object -Property Depth -Descending}
Default {$objects}
})
}
end {
}
}
function ConvertTo-PreActionPath {
<#
.SYNOPSIS
Convert to new path with extention .zip or adding time stamp.
.DESCRIPTION
Find convert type in the -PreAction option.
-PreAction Compress, Archive, 7z, 7zZip, AddTimeStamp are supported.
Convert to new path with extention .zip or adding time stamp with the convert type.
.PARAMETER PATH
Specify a file path to convert.
.PARAMETER DESTINATIONPATH
Specify a desitination folder path.
Even if you do not specify -PreAction MoveNewFile, you need specify the desitination path.
.INPUT
System.String. Path of the file
.OUTPUT
PSobject
#>
[OutputType([PSObject])]
[CmdletBinding()]
Param(
[String][parameter(position = 0 ,mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)][Alias("TargetObject" , "FullName")]$Path ,
[String][parameter(position = 1 ,mandatory, ValueFromPipelineByPropertyName)][Alias("destinationFolder")]$DestinationPath ,
[Array]$PreAction = $PreAction ,
[String]$CompressedExtString = $CompressedExtString ,
[String]$TimeStampFormat = $TimeStampFormat
)
begin {
$archive = New-Object PSObject -Property @{
Path = ''
Type = ''
}
}
process {
IF (($PreAction -match '^(Compress|Archive)$')) {
#Switch find all elements in [Array]$PreAction
#Find an element '7z' or '7zZip' in the array till finding one.
Switch -Regex ($PreAction) {
'^7z$' {
$archive.Type = "7z"
$extension = '.7z'
Break
}
'^7zZip$' {
$archive.Type = "7zZip"
$extension = '.zip'
Break
}
Default {
$archive.Type = ''
$extension = $CompressedExtString
}
}
} else {
$archive.Type = ''
$extension = ''
}
Switch -Regex ($PreAction) {
'^Compress$' {
$archive.Type += "Compress"
Break
}
'^Archive$' {
$archive.Type += "Archive"
Break
}
Default {
}
}
IF ($PreAction -contains 'AddTimeStamp') {
$archive.Path = $DestinationPath |
Join-Path -ChildPath (($Path | Split-Path -Leaf | ConvertTo-FileNameAddTimeStamp -TimeStampFormat $TimeStampFormat) + $extension)
$archive.Type += $(IF ($PreAction -match '^(Compress|Archive)$') {"AndAddTimeStamp"}