-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEmbroideryCollection-Cleanup.ps1
4074 lines (3611 loc) · 161 KB
/
EmbroideryCollection-Cleanup.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 5.1
<#
EmbroideryCollection-Cleanup.ps1
GPL-3.0 license
Deal with the many different types of embroidery files, put the right format types in mySewingnet Cloud or onto a USB drive
We are looking to keep the ??? files types only from the zip files.
Orginal Author: Darren Jeffrey, Dec 2021 - Feb 2025
#>
param
(
[Parameter(Mandatory = $false)]
[int32]$DownloadDaysOld, # How many days old show it scan for Zip files in Download
[int32]$SetSize = 5,
[Switch]$KeepAllTypes, # Keep all the different types of a file (duplicate name but different extensions)
[Switch]$CleanCollection, # Cleanup the Collection Folder to only EmbroidDir files
# incomplete NoDirectory
# [Switch]$NoDirectory, # Do not create directory structure in the upload from space
# [Switch]$OneDirectory, #Limit the folders to one directly deep only
[string]$EmbroidDir = "Embroidery", # You may want to change this directory name inside of the 'Collection ' Directory wihtin your 'Documents' directory
# If it is just a name, then it is assumed to be within the defeault Documents directory, otherwise it will be taken as a full path
[string]$USBDrive, # Write the output to a USB Drives
[switch]$USBEject, # Write the output to a USB Drives
[Switch]$HardDelete, # Delete the files rather than sending to recycle bin
[switch]$KeepEmptyDirectory, # If you don't want this to remove extra empty directories from Collection folders'
[Switch]$Testing, # Run it and see what happens
[Switch]$Setup, # Setup the Shortcut on the desktop to this application
[Switch]$DragUpload, # Use the web page instead of the plug in to drag and drop
[Switch]$ShowExample, # Show the example GIF
[string]$ConfigFile = "EmbroideryCollection.cfg", # This is the file in the same directory as this script otherwise it is a full path (Not recommened to change)
[Switch]$ConfigDefault, # Got back to default settings
[Switch]$SwitchDefault, # Clear all the preview Switch enabled Values
[Switch]$FirstRun, # Scan all the ZIP files
[Switch]$Sync, # Sync MySewnet to local folders
[Switch]$CloudAPI, # use MySewNet cloud API
[String]$OldVersion # Used during upgrade only
)
$ECCVERSION = "v0.8.6"
$GitOwner = "D-Jeffrey"
$GitName = "Embroidery-File-Organize"
$ECCNAME = "Embroidery Collection Cleanup"
# $VerbosePreference = "Continue"
# $InformationPreference = "Continue"
<# ******** CONFIGURATION ********#>
$preferredSewType = 'vp4', 'vp3', 'pes', 'pcs','hus','dst'
$alltypes = 'art', 'art50', 'art60', 'art70', 'art80', 'asd', 'bmc', 'cnd', 'csd', 'dem', 'dst', 'dxf', 'emb', 'emd', 'ese', 'exp', 'gnc', 'hus', 'jef', 'jef+', 'jpx', 'mhv', 'oef', 'ofm', 'pcd', 'pcm', 'pcq', 'pcs', 'pec', 'pel', 'pem', 'pes', 'phb', 'phc', 'pxf', 'sew', 'shv', 'svg', 'tap', 'vf3', 'vip', 'vp3', 'vp4', 'xxx', 'zsk'
$defaultfoldupDir = 'images', 'sewing helps', 'Designs', 'Design Files', 'brother-babylock-pes', 'janome-jef', 'singer-xxx', 'husqvarna-viking-hus', 'commercial formats - dst-exp', 'artista-art','vp'
$defaultgoodInstructionTypes = 'avi', 'bmp', 'doc', 'docx', 'emf', 'gif', 'htm', 'html', 'jpg', 'm4v', 'mov', 'mp4', 'mpg', 'pcx', 'pdf', 'png', 'ppt', 'pptx', 'rtf', 'tif', 'txt', 'wmf', 'wmv'
$defaultTandCs = 'TERMS-OF-USAGE.*', 'planetappliquetermsandconditions.*','READ ME FIRST.rtf','*copyright.*','*copyright Statement.*','*copyrights.*',
'copyrightStatement.*','License agreement.*', 'License.*','termsofuse.*', 'Thumbs.db'
<# ******** END CONFIGURATION - active settings kept in EmbroideryCollection.cfg ********#>
# List of paramstring to check
$paramstring = [ordered]@{
'EmbroidDir' = 'Embriodary Files directory';
'USBDrive'='USB drive letter (example E: or H:)';
'LastCheckedGithub'='';
'LatestTag'='';
'DownloadDaysOld' = 'Age of zip files in Download directory';
'SetSize' = 'Keep collections of files together if there are at least this many'
}
$parambool = [ordered]@{
'KeepAllTypes'= 'Keep all variations of files types' ;
'KeepEmptyDirectory'= 'When cleaning up keep empty folders';
'DragUpload'= 'Open the mysewnet Cloud browser interface for drag and drop';
'ShowExample'= 'Show how to upload to mySewnet';
'NoDirectory'= 'Do not use Directories from Zip files which creating collection';
'OneDirectory'= 'Keep files a maximum of one directory deep ';
'CloudAPI'= 'Use MySewnet Cloud';
'USBEject'='Safely Eject the USB drive when complete'
}
$paramarray = [ordered]@{
'preferredSewType' = 'The preferred types of Embriodary file types';
'alltypes' = '* All the possible types of files which are an Embriodary file';
'foldupDir' = '* Remove/fold folders of this name';
'goodInstructionTypes' = '* Instructions file types which should be saved with files';
'TandCs' = '* Readme, Copyright files and T&C'
}
$paramswitch =[ordered]@{
'CleanCollection' = 'Clean the Collection folder';
'CloudAPI' = "Using API to update mySewNet Cloud (It is buggy, try again if you get errors/warnings)";
'Sync' = 'Syncronize computer folders to Cloud'
}
# ----------------------------------------------------------------------
# $alltypes
# this is a list of all the different types of embrodiary files that are considered. The '$preferredSewType' should be from the list below based on what is best for your
# machine and in the order that you prefer. If there are more than one copy of a file type it will select your first one
# ----------------------------------------------------------------------
# $TandCs
# Term and Conditions added by various store that add up space with the same document type over and over, using up your MySewing Cloud space
# This is a file name pattern so TC.* will match TC.doc or TC.pdf
# ----------------------------------------------------------------------
# $foldupDir
# What directories should be flattened to bring the Embroidery files higher up so they are not nested instead of sub-folders.
# The names are for Directories you want to remove the sub-folder and moved the contents up
# ----------------------------------------------------------------------
write-progress -Activity "Starting" -Status "Starting Embroidery Collection Cleanup : $ECCVERSION on PS $($PSVersionTable.PSVersion.major).$($PSVersionTable.PSVersion.minor) " -PercentComplete 5
$RemovePrefix = ($PSVersionTable.PSVersion.Major -lt 7 )
if ($RemovePrefix) {
write-host " ".padright(15) " (Runs better with a new version of Powershell)".padright(70) -ForegroundColor Yellow -BackgroundColor Blue
}
$script:RemoveFilecnt = 0
$script:RemoveFileSize = 0
$Script:RemoveDirCnt = 0
$Script:savecnt = 0
$Script:addsizecnt = 0
$Script:p = 0
$padder = 45
$use7zipsize = 1024*1024*100 # 100 MB switch to 7zip if it is install for zip files over 100 MB, if 7zip is installed
$filesToRemove = @()
$script:lostfiles = @()
$script:CloudStatusGood = $true
$script:CloudAuthAvailable = $false
$script:markdrive = "eCollection.txt"
$shell = New-Object -ComObject 'Shell.Application'
$downloaddir = (New-Object -ComObject Shell.Application).NameSpace('shell:Downloads').Self.Path
if (!(test-path $downloaddir)) {
Write-Error "The Download Directory does not work, please correct the script"
return
}
$docsdir =[environment]::getfolderpath("mydocuments")
if ($docsdir.tolower().contains('\onedrive')) {
$docsdir = ${env:HOMEDRIVE} + ${env:HOMEPATH}
}
$tmpdir = ${env:temp} + "\cleansew.tmp"
$opencloudpage = "https://www.mysewnet.com/en-us/my-account/#/cloud/"
$upgradescript = Join-Path -Path $PSScriptRoot -ChildPath "install.ps1"
$missingSewnetAddin = (get-itemproperty -ErrorAction SilentlyContinue -path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{E2F80510-8B1C-4A23-B657-D173D4F6E418}")."(default)" -notlike "VsmSoftware*"
$script:protime = $(get-date)
#
# Read and process the Config File
#
# Check if the ConfigFile path is not absolute
if (!$ConfigFile.Contains('\')) {
# If it's a file only, join it with the script root path
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath $ConfigFile
}
# If ConfigDefault and ConfigFile exists, remove the ConfigFile
if ($ConfigDefault -and (Test-Path -Path $ConfigFile)) {
Remove-Item -Path $ConfigFile | out-null
}
# If ConfigFile exists, read its content and convert from JSON
if (Test-Path -Path $ConfigFile) {
# Get the content of the configuration file and convert it from JSON
$SavedParam = Get-Content -Path $ConfigFile -Encoding Utf8 -ErrorAction SilentlyContinue | ConvertFrom-Json
# Iterate over each parameter
if ($null -eq $SwitchDefault) {
$paralist = ($paramstring.Keys)
} else {
$paralist = ($paramstring.Keys + $parambool.Keys)
}
foreach ($param in ($paralist)) {
# Use variable indirection to check if the parameter is present
$isParamPresent = $PSBoundParameters.ContainsKey($param)
# If the parameter is not present and it exists in the saved parameters, assign the saved value
if (-not $isParamPresent -and $null -ne $SavedParam.$param) {
Set-Variable -Name $param -Value $SavedParam.$param
# write-host "$param = " $SavedParam.$param
}
# toggle a Switch Option
if ($isParamPresent -and ($parambool.Contains($param))) {
Set-Variable -Name $param -Value (-not $SavedParam.$param)
}
}
foreach ($param in ($paramarray.Keys)) {
if ($null -ne $SavedParam.$param) {
$newvalue = $SavedParam.$param.value
if ($null -eq $newvalue) {
$newvalue = $SavedParam.$param
}
Set-Variable -Name $param -Value $newvalue
}
}
} else {
$FirstRun = $true
}
####################### CLASS ###################
####################### Functions ###################
#-#-#-#-#-
function SaveAllParams
{
# Save the state of the variables and settings
$SavedParam = New-Object PSObject
# Iterate over each variable name
foreach ($param in ($parambool.Keys)) {
$val = [bool](Get-Variable -Name $param -ValueOnly)
# Add each variable to the object as a NoteProperty
$SavedParam | Add-Member -MemberType NoteProperty -Name $param -Value $val
}
foreach ($param in ($paramstring.Keys + $paramarray.keys)) {
$val = (Get-Variable -Name $param -ValueOnly)
$SavedParam | Add-Member -MemberType NoteProperty -Name $param -Value $val
}
# Convert the object to a JSON string and save it to a file
$SavedParam | ConvertTo-Json | Set-Content -Path $ConfigFile -Encoding Utf8
}
Function PrepareCloud() {
if ($CloudAPI) {
AdvanceProgress "Preparing Authenication Module" -BigStep
$script:CloudAuthAvailable = ((Get-Module -Name PSAuthClient).count -gt 0)
if (-not $script:CloudAuthAvailable) {
AdvanceProgress "Checking for Authenication Module" -BigStep
if ((Get-Module -ListAvailable | Where-Object { $_.Name -eq "PSAuthClient" }).count -gt 0) {
write-verbose "Importing PSAuthClient"
Import-Module PSAuthClient
$script:CloudAuthAvailable = ((Get-Module -Name PSAuthClient).count -gt 0)
}
else {
AdvanceProgress "-- Please wait while the script installs missing module --" -BigStep
write-verbose "Install+Importing PSAuthClient"
Install-Module -name PSAuthClient -scope:CurrentUser
Import-Module PSAuthClient
$script:CloudAuthAvailable = ((Get-Module -Name PSAuthClient).count -gt 0)
write-host "Completed" -foreground Yellow
}
Complete-Progress
}
if (-not $script:CloudAuthAvailable) {
Write-host "Using API to update mySewNet Cloud requires PSAuthClient to be installed to use CloudAPI feature" -ForegroundColor Red
}
}
}
function Show-Progress {
param (
[Parameter(Mandatory = $false)]
[string]$Activity,
[string]$Status,
[int]$PercentComplete,
[Switch]$Completed
)
$params = @{}
if ($(get-date).AddSeconds(-1) -gt $script:protime) {
if ($Activity) { $params.Activity = $Activity }
if ($Status) { $params.Status = $Status }
if ($PercentComplete) { $params.PercentComplete = [Math]::max(1,[Math]::min(100,$PercentComplete))}
if ($Completed) { $params.Completed = $Completed}
Write-Progress @params
$script:protime = $(get-date)
}
}
function Complete-Progress {
$script:protime = (get-date).AddMinutes(-2)
Show-Progress -Completed $true
}
#=============================================================================================
function LogAction($File, $Action, [Boolean]$isInstructions = $false) {
$now = Get-Date -Format "yyyy/MMM/dd HH:mm "
$extra = (&{if ($isInstructions) { "Instruct "} else { "Embroidery" } })
write-verbose "$Action type:$extra $File"
Add-Content -Path $LogFile -Value ("$now$Action $extra $File ") -ErrorAction SilentlyContinue
}
Function AdvanceProgress {
param (
[Parameter(Mandatory = $false)]
[string]$Activity, [string]$status = $null, [switch]$BigStep)
$Script:p++
if ($BigStep) {
$Script:p = $Script:p + 9 ;
$script:protime = (get-date).AddMinutes(-1)
}
if ($status) {
Show-Progress -PercentComplete ($Script:p % 100 ) -Activity $Activity -Status $status
} else {
Show-Progress -PercentComplete ($Script:p % 100 ) -Activity $Activity
}
}
# Delete or recycle a file (full path required)
Function RecycleFile {
param (
[System.IO.FileInfo[]]$file,
[boolean]$purge )
if (-not ($file)) {
write-warning 'Recycle blank name'
return
}
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class FileOperation {
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHFILEOPSTRUCT {
public IntPtr hwnd;
[MarshalAs(UnmanagedType.U4)]
public int wFunc;
public string pFrom;
public string pTo;
public short fFlags;
[MarshalAs(UnmanagedType.Bool)]
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
public string lpszProgressTitle;
}
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
public const int FO_DELETE = 3;
public const int FOF_ALLOWUNDO = 0x40;
public const int FOF_NOCONFIRMATION = 0x10; // Don't prompt the user.
}
"@
foreach ($thisfile in $file) {
#BUG-FIX? Long File name detection
$thisfile = Get-Item $thisfile.FullName
if ($thisfile.Attributes -band [IO.FileAttributes]::Readonly) {
$thisfile.Attributes = $thisfile.Attributes -bxor [IO.FileAttributes]::Readonly
}
try {
if ($purge) {
$path = if ($RemovePrefix) { "\\?\$($thisfile.FullName)" } else { $thisfile.FullName }
Remove-Item -Path $path -Force -ErrorAction Stop | out-null # Handled by WhatIf
} elseif ($doit) {
if ($RemovePrefix) {
$shell.NameSpace(17).ParseName($thisfile).InvokeVerb('delete')
} else {
#Faster PS 7 version
$fileOp = New-Object FileOperation+SHFILEOPSTRUCT
$fileOp.wFunc = [FileOperation]::FO_DELETE
$fileOp.pFrom = $thisfile.FullName + [char]0
$fileOp.fFlags = [FileOperation]::FOF_ALLOWUNDO -bor [FileOperation]::FOF_NOCONFIRMATION
[FileOperation]::SHFileOperation([ref]$fileOp) | Out-Null
}
}
} catch {
write-warning "Problem deleting: $thisfile - $($thisfile.Fullname)"
}
}
}
function MyPause {
param (
[string]$Message,
[switch]$Choice,
[string]$BoxMsg,
[int]$Timeout = 0,
[bool]$useGUI = $false,
[bool]$ChoiceDefault = $true,
# If this is included, then the first key will be used for it and this value will be returned instead of a true/false
[string]$extraChoice = ""
# [bool]$YesNoCancel = $false
)
$bKeys = ""
$yes = $true
# Check if running Powershell ISE
if ($psISE -or $useGUI) {
Add-Type -AssemblyName "System.Windows.Forms"
$BoxMsg = if ($BoxMsg -eq "" -or $null -eq $BoxMsg) { $Message } else { $BoxMsg }
if ($Choice) {
$x = [System.Windows.Forms.MessageBox]::Show($BoxMsg, 'Embroidery Collection Cleanup', 'YesNo', 'Question')
} else {
[System.Windows.Forms.MessageBox]::Show($BoxMsg, 'Embroidery Collection Cleanup')
}
$yes = ($x -eq 'Yes')
} else {
$secondsRunning = 0
if ($Timeout -gt 0) {
Start-Sleep -Milliseconds 100
$host.ui.RawUI.FlushInputBuffer()
}
if ($choice) {
$Message += if ($Message -notlike "*?") { "?" } else { "" }
$extraKeys = if ($extraChoice) { "/" + $extraChoice.ToLower() } else { "" }
$yesno = if ($ChoiceDefault) { " (Y/n$extraKeys) " } else { " (y/N$extraKeys) " }
} else {
$yesno = ""
}
Complete-Progress
Write-Host ($Message + $yesno ) -ForegroundColor Yellow -NoNewline
$yes = $ChoiceDefault
$needakey = $true
while ($needakey) {
while (-not $Host.UI.RawUI.KeyAvailable -and $secondsRunning++ -lt $Timeout*2) {
Start-Sleep -Milliseconds 500
if ($timeout) {
$timeremain = [math]::floor(($timeout*2 - $secondsRunning)/2).tostring()
if ($Host.UI.RawUI.KeyAvailable) {$i = "-" } else{ $i= " "}
write-host "$($timeremain.padleft(6))$i`b`b`b`b`b`b`b" -NoNewline -ForegroundColor Blue}
}
$needakey = ($Timeout -ne 0 -and $secondsRunning++ -lt $Timeout*2)
if ($Host.UI.RawUI.KeyAvailable -or $Timeout -eq 0) {
$keystroke = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$yes = 'Yy'.Contains($keystroke.Character)
# Look for yes or no keystrokes
if ($choice) {
$needakey = -not ("YyNn$bKeys".Contains($keystroke.Character))
} else {
$needakey = $false
}
# Use the Default selection if the ENTER key is pressed
if ($keystroke.VirtualKeyCode -eq 13) {
$needakey = $false
$yes = $ChoiceDefault
}
Start-Sleep -Milliseconds 100
$host.ui.RawUI.FlushInputBuffer()
}
}
if ($timeout) { write-host " `b`b`b`b`b`b" -NoNewline }
if ($choice) {
$selectchoice = (&{if ($yes) { "Yes"} else { "No" } })
if ($extraChoice -and $bKeys.Contains($keystroke.Character) ) {
$selectchoice = $extraChoice
$yes = $extraChoice
}
write-host $selectchoice
} else {
Write-Host " "
}
}
return $yes
}
function doWinForm() {
Write-Progress -Activity "Preparing" -PercentComplete 50
Add-Type -AssemblyName "System.Windows.Forms"
$ico = "C:\ProgramData\EmbroideryOrganize\EmbroideryManager.ico"
# Create the form
$script:form = New-Object System.Windows.Forms.Form -Property @{
Text = $ECCNAME
width=800
height=500
StartPosition = "CenterScreen"
BackColor = "Window"
Font = "Calibri, 9pt"
AutoScaleMode = 'Dpi'
AutoSizeMode = 'GrowAndShrink'
}
if (test-path -path $ico) {
$form.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($ico)
} else {
$form.ShowIcon = $False
}
$lbl_title = New-Object System.Windows.Forms.Label -Property @{
BackColor="Blue"
Font="Arial Black, 16pt"
ForeColor="White"
Width= 800
Height= 32
#TextAlign="TopCenter"
Text = " Embroidery Collection Cleanup $ECCVERSION"
}
$lbl_subtitle = New-Object System.Windows.Forms.Label -Property @{
BackColor="Blue"
Font="8pt"
ForeColor="White"
Width= 800
Height= 14
Location = New-Object System.Drawing.Point(0, 32)
Text = "(on PowerShell $($PSVersionTable.PSVersion.major).$($PSVersionTable.PSVersion.minor))"
Padding="670, 0, 0, 0"
}
$form.Controls.Add($lbl_title)
$form.Controls.Add($lbl_subtitle)
# Any notifications for users go into here
$script:InfoText = @{}
# Create a panel to hold the parameters
$panel = New-Object System.Windows.Forms.Panel -Property @{
Location = New-Object System.Drawing.Point(125, 48)
Width= 668
Height= 450
Font="Tahoma,9pt"
}
$lbl_EmbrodRootDirtop = New-Object System.Windows.Forms.Label -Property @{
Location = New-Object System.Drawing.Point(4, 12)
Width= 120
Height= 21
Text="Embroidery base dir"
}
$lbl_DownloadDaysOld = New-Object System.Windows.Forms.Label -Property @{
Location = New-Object System.Drawing.Point(4, 36)
Width= 120
Height= 21
Text="Download days old"
}
if ($script:FirstRun) {
$lbl_Onetime = New-Object System.Windows.Forms.Label -Property @{
Location = New-Object System.Drawing.Point(215, 36)
Width= 300
Height= 17
AutoSize = $true
Text="Checking all zips in Download folder, 'Download days old' ignored this time"
Padding="5, 3, 5, 0"
ForeColor= "ActiveCaptionText"
BackColor= "ActiveCaption"
}
$panel.Controls.Add($lbl_Onetime)
$script:InfoText.Firstrun = "This is a first run, and we will check all the zip files in the download directory`n"
}
$lbl_KeepAlltypes= New-Object System.Windows.Forms.Label -Property @{
Location = New-Object System.Drawing.Point(4, 60)
Width= 120
Height= 21
Text="Keep all types"
}
$lbl_location= New-Object System.Windows.Forms.Label -Property @{
Location = New-Object System.Drawing.Point(4, 204)
Width= 120
Height= 21
Text="Output to"
}
$script:lbl_Info= New-Object System.Windows.Forms.Label -Property @{
Location = New-Object System.Drawing.Point(4, 294)
Width= 600
Height= 91
Text=""
Padding="5, 5, 5, 5"
ForeColor="InfoText"
BackColor="Info"
BorderStyle = "FixedSingle"
}
if ($script:latestTag -gt $ECCVERSION) {
$centerpnt = ($lbl_Info.size.Width - $lbl_Info.Location.X - 150 ) / 2
$lbl_newver = New-Object System.Windows.Forms.Button -Property @{
Location = New-Object System.Drawing.Point($centerpnt, 387)
Width= 150
Height= 18
Autosize = $true
Text="New version avaiable: " + $script:LatestTag
Font="8pt"
ForeColor="ActiveCaptionText"
BackColor="ActiveCaption"
}
if (test-path $upgradescript) {
$lbl_newver.Text = $lbl_newver.Text + " - Click here to update"
$lbl_newver.Add_Click({
$script:exitmode = "Upgrade"
$form.Close()
})
}
$panel.Controls.Add($lbl_newver)
}
$panel.Controls.Add($lbl_EmbrodRootDirtop)
$panel.Controls.Add($lbl_DownloadDaysOld)
$panel.Controls.Add($lbl_KeepAlltypes)
$panel.Controls.Add($lbl_location)
$panel.Controls.Add($lbl_Info)
$tbx_EmbrodRootDirtop = New-Object System.Windows.Forms.TextBox -Property @{
Location = New-Object System.Drawing.Point(130, 12)
Width=380
Height=20
Text = $script:EmbroidDir
}
$panel.Controls.Add($tbx_EmbrodRootDirtop)
$DirectoryBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
SelectedPath = $script:EmbroidDir
Description = "Select the Directory for Embroidery Files. This will be used as a reference location for you to look at the current collection of files"
ShowNewFolderButton = $true
# https://learn.microsoft.com/en-us/dotnet/api/system.environment.specialfolder
rootFolder = 40 # CommonDocuments
}
$btn_selectDir = New-Object System.Windows.Forms.Button -Property @{
Text = "Select Directory"
BackColor="LightSkyBlue"
UseVisualStyleBackColor=$False
Location = New-Object System.Drawing.Point(511, 9)
Width=99
Height=23
}
$btn_selectDir.Add_Click({
$DirectoryBrowser.SelectedPath = $script:EmbroidDir
# Update the variables with the current values in the controls
if ($DirectoryBrowser.ShowDialog() -eq "OK") {
$script:EmbroidDir = $DirectoryBrowser.SelectedPath
$tbx_EmbrodRootDirtop.Text = $script:EmbroidDir
}
})
$panel.Controls.Add($btn_selectDir)
$btn_open = New-Object System.Windows.Forms.Button -Property @{
Text = "Open"
Location = New-Object System.Drawing.Point(613,9)
Width= 43
Height= 23
BackColor="LightSkyBlue"
}
$btn_open.Add_Click({
$odir = $tbx_EmbrodRootDirtop.Text
Invoke-expression "explorer ""$odir"""
})
$panel.Controls.Add($btn_open)
if ($script:DownloadDaysOld -lt 1) { $script:DownloadDaysOld = 7 }
$nud_DownloadDaysOld = New-Object System.Windows.Forms.NumericUpDown -Property @{
Location = New-Object System.Drawing.Point(130, 36)
Width=67
Height=20
Value = $script:DownloadDaysOld
Minimum = 1
Maximum = 9000
}
$panel.Controls.Add($nud_DownloadDaysOld)
$cbx_KeepAllTypes = New-Object System.Windows.Forms.CheckBox -Property @{
Location = New-Object System.Drawing.Point(130, 58)
Checked = ($true -eq $script:KeepAllTypes)
}
$panel.Controls.Add($cbx_KeepAllTypes)
$panelPref = New-Object System.Windows.Forms.Panel -Property @{
Location = New-Object System.Drawing.Point(2, 82)
Width= 480
Height= 114 # 204-82
BorderStyle = "FixedSingle"
}
$panel.Controls.Add($panelPref)
$lbl_preferredSewType= New-Object System.Windows.Forms.Label -Property @{
Location = New-Object System.Drawing.Point(2, 2)
Width= 120
Height= 62
Text="Preferred sewing`nfiles selected`nin this order"
}
$lbl_otherSewType= New-Object System.Windows.Forms.Label -Property @{
Location = New-Object System.Drawing.Point(362, 2)
Width= 170
Height= 82
Text="Other sewing file`ntypes.`nAdd if they are`nsupported by`nyour machine"
}
$panelPref.Controls.Add($lbl_preferredSewType)
$panelPref.Controls.Add($lbl_otherSewType)
$lbx_preferredSewType = New-Object System.Windows.Forms.ListBox -Property @{
Location = New-Object System.Drawing.Point(128, 4)
Width=68
Height=110
SelectionMode = [System.Windows.Forms.SelectionMode]::One
}
$panelPref.Controls.Add($lbx_preferredSewType)
$lbx_otherTypes = New-Object System.Windows.Forms.ListBox -Property @{
Location = New-Object System.Drawing.Point(285, 4)
Width=68
Height=110
SelectionMode = [System.Windows.Forms.SelectionMode]::One
}
$panelPref.Controls.Add($lbx_otherTypes)
# Populate the ListBox with sample items
$lbx_preferredSewType.Items.AddRange($preferredSewType)
$lbx_otherTypes.Items.AddRange($($alltypes |where-object {$_ -notin $preferredSewType}))
# Create the Move Up button
$lbbx_moveUpButton = New-Object System.Windows.Forms.Button -Property @{
Text = "↑"
Location = New-Object System.Drawing.Point(198, 8)
Width=20
Height=20
}
$lbbx_moveUpButton.Add_Click({
$selectedIndex = $lbx_preferredSewType.SelectedIndex
if ($selectedIndex -gt 0) {
$temp = $lbx_preferredSewType.Items[$selectedIndex - 1]
$lbx_preferredSewType.Items[$selectedIndex - 1] = $lbx_preferredSewType.Items[$selectedIndex]
$lbx_preferredSewType.Items[$selectedIndex] = $temp
$lbx_preferredSewType.SelectedIndex = $selectedIndex - 1
}
})
$panelPref.Controls.Add($lbbx_moveUpButton)
$lbbx_moveAddButton = New-Object System.Windows.Forms.Button -Property @{
Text = "←"
Location = New-Object System.Drawing.Point(238, 26)
Width=30
Height=20
}
$lbbx_moveAddButton.Add_Click({
$selectedIndex = $lbx_otherTypes.SelectedIndex
if ($selectedIndex -ge 0) {
$lbx_preferredSewType.Items.Add($lbx_otherTypes.Items[$selectedIndex])
$lbx_otherTypes.Items.RemoveAt($selectedIndex)
}
})
$panelPref.Controls.Add($lbbx_moveAddButton)
$lbbx_moveRmButton = New-Object System.Windows.Forms.Button -Property @{
Text = "→"
Location = New-Object System.Drawing.Point(238, 51)
Width=30
Height=20
}
$lbbx_moveRmButton.Add_Click({
$selectedIndex = $lbx_preferredSewType.SelectedIndex
if ($selectedIndex -ge 0) {
$lbx_otherTypes.Items.Add($lbx_preferredSewType.Items[$selectedIndex])
$lbx_preferredSewType.Items.RemoveAt($selectedIndex)
}
})
$panelPref.Controls.Add($lbbx_moveRmButton)
# Create the Move Down button
$lbbx_moveDnButton = New-Object System.Windows.Forms.Button -Property @{
Text = "↓"
Location = New-Object System.Drawing.Point(198, 76)
Width=20
Height=20
}
$lbbx_moveDnButton.Add_Click({
$selectedIndex = $lbx_preferredSewType.SelectedIndex
if ($selectedIndex -ge 0 -and $selectedIndex -lt $lbx_preferredSewType.Items.Count - 1) {
$temp = $lbx_preferredSewType.Items[$selectedIndex + 1]
$lbx_preferredSewType.Items[$selectedIndex + 1] = $lbx_preferredSewType.Items[$selectedIndex]
$lbx_preferredSewType.Items[$selectedIndex] = $temp
$lbx_preferredSewType.SelectedIndex = $selectedIndex + 1
}
})
$panelPref.Controls.Add($lbbx_moveDnButton)
if ($script:CloudAPI) {
$script:USBDrive = "MySewnet"
}
################# Local Functions ##############
# Query Win32_LogicalDisk class to get information about drives
function refeshDriveList() {
# Filter and list removable drives
# calling this triggers the import the slower to load functions in Microsoft.PowerShell.Management
$removableDrives = Get-WmiObject -Class Win32_LogicalDisk | Where-Object { $_.DriveType -eq 2 }
return $removableDrives
}
function isDriveReady($drv) {
return (Get-WmiObject -Class Win32_LogicalDisk | Where-Object { $_.DriveType -eq 2 -and $_.FreeSpace -gt 0 -and $_.DeviceID -like $drv })
}
function updateDriveList() {
$items = @("None", "mySewNet")
$removableDrives = refeshDriveList
$items = @()
$items += "None"
$items += "mySewNet"
foreach ($drv in $removableDrives.DeviceID) {
$items += $drv
}
# Clear the ComboBox and add the new items
$cmb_location.Items.Clear()
$cmb_location.Items.AddRange($items)
$i = 0
$driveletter = $script:USBDrive | split-path -Qualifier -ErrorAction SilentlyContinue
if ($null -eq $driveletter) {
$driveletter = $script:USBDrive
}
$btn_open2.Enabled = $false
foreach ($sel in $items ) {
if ($sel -like ($driveletter)) {
$cmb_location.SelectedIndex = $i
$btn_open2.Enabled = $true
}
$i = $i + 1
}
if ("" -eq $USBDrive ) {
$cmb_location.SelectedIndex = 0
$btn_open2.Enabled = $false
}
}
$cmb_location = New-Object System.Windows.Forms.ComboBox -Property @{
Location = New-Object System.Drawing.Point(130, 204)
DropDownStyle = "DropDownList"
}
function driveComboChange ()
{
if ($btn_go) {
$btn_go.Enabled = $true
$btn_sync.Enabled = $true
$btn_clean.Enabled = $true
}
if ($cbx_usbeject) {
$d = $cmb_location.Items[$cmb_location.SelectedIndex]
$cbx_usbeject.Enabled = ($cmb_location.SelectedIndex -gt 1)
$lbl_usbeject.Enabled = $cbx_usbeject.Enabled
$btn_open2.Enabled = $cbx_usbeject.Enabled
$cbx_openmySewnet.Enabled = $cmb_location.SelectedIndex -in (0,1)
if (($cmb_location.SelectedIndex -eq 0)) {
$script:InfoText.Sync = ""
}
if (($cmb_location.SelectedIndex -eq 1)) {
$script:InfoText.Sync = "Note: 'Sync'ing to MySewnet will remove files, in addition to adding them`n"
$script:InfoText.ready = ""
} elseif (($cmb_location.SelectedIndex -gt 1)) {
$script:InfoText.Sync = ""
if (isDriveReady -drv $d) {
if (-not $(test-path -path $(join-path -Path $d -ChildPath $markdrive))) {
$script:InfoText.ready = "USB Drive $d has not been used with this for Embrodary files.`nUse the Sync button copy your Embroidery collection to a new stick`n"
}
else {
$script:InfoText.ready = ""
}
} else {
$script:InfoText.ready = "USB Drive $d is not ready`nInsert USB drive and click refresh`n"
if ($btn_go) {
$btn_go.Enabled = $false
$btn_sync.Enabled = $false
$btn_clean.Enabled = $false
}
}
}
}
if ($cmb_location.SelectedIndex -eq -1 -and $btn_go) {
$btn_go.Enabled = $false
$btn_sync.Enabled = $false
$btn_clean.Enabled = $false
$script:InfoText.insert = "Select an different output (or insert your USB drive and click refresh)`n"
} else {
$script:InfoText.insert = ""
}
if ($btn_sync) {
$btn_sync.Enabled = ($cmb_location.SelectedIndex -ne 0 -and $btn_go.Enabled)
}
Invoke-command -ScriptBlock $scriptblock_CalcInfoText
}
$cmb_location.Add_SelectionChangeCommitted( {driveComboChange})
$btn_refreshDir = New-Object System.Windows.Forms.Button -Property @{
Text = "Refresh"
BackColor="LightSkyBlue"
UseVisualStyleBackColor=$False
Location = New-Object System.Drawing.Point(260, 204)
Width=59
Height=23
}
$btn_refreshDir.Add_Click({
$sav = $cmb_location.SelectedIndex
if ($cmb_location.SelectedIndex -ge 0) {
$cmb_location.Items[$cmb_location.SelectedIndex]
$script:USBDrive = $cmb_location.Items[$cmb_location.SelectedIndex]
}
updateDriveList
driveComboChange
if (-1 -eq $cmb_location.SelectedIndex) {
$cmb_location.SelectedIndex =$sav
}
})
$panel.Controls.Add($btn_refreshDir)
$panel.Controls.Add($cmb_location)
$btn_open2 = New-Object System.Windows.Forms.Button -Property @{
Text = "Open"
Location = New-Object System.Drawing.Point(329,204)
Width= 43
Height= 23
BackColor="LightSkyBlue"
Enabled = $false
}
$btn_open2.Add_Click({
$odir = $cmb_location.Items[$cmb_location.SelectedIndex]
Invoke-expression "explorer ""$odir"""
})
$panel.Controls.Add($btn_open2)
# Create a panel to hold control buttons
$panelEject = New-Object System.Windows.Forms.Panel -Property @{
Location = New-Object System.Drawing.Point(24, 234)
Width= 135
Height= 38
BorderStyle ="FixedSingle"
}
$lbl_usbeject= New-Object System.Windows.Forms.Label -Property @{
Location = New-Object System.Drawing.Point(2, 2)
Width= 100
Height= 31
Text="Safely Eject USB when done"
}
$panelEject.Controls.Add($lbl_usbeject)
$cbx_usbeject = New-Object System.Windows.Forms.CheckBox -Property @{
Location = New-Object System.Drawing.Point(106, 2)
Width= 15
Height= 15
Checked = $USBEject
Enabled = $script:USBEject
}
$panelEject.Controls.Add($cbx_usbeject)
$panel.Controls.Add($panelEject)
$panelMysew = New-Object System.Windows.Forms.Panel -Property @{
Location = New-Object System.Drawing.Point(214, 234)
Width= 213
Height= 38
BorderStyle ="FixedSingle"
}
$lbl_openmySewnet = New-Object System.Windows.Forms.Label -Property @{
# Location = New-Object System.Drawing.Point(184, 234)
Location = New-Object System.Drawing.Point(2, 2)
Width= 100
Height= 31
Text="Open MySewnet Cloud when done"
}
$panelMysew.Controls.Add($lbl_openmySewnet)
$cbx_openmySewnet = New-Object System.Windows.Forms.CheckBox -Property @{
Location = New-Object System.Drawing.Point(110, 2)
Width= 15
Height= 15
Checked = $script:DragUpload
}
$panelMysew.Controls.Add($cbx_openmySewnet)
if (test-path -path $(${env:temp} + "\cleansew.new")) {
$btn_open3 = New-Object System.Windows.Forms.Button -Property @{
Text = "Last New`nFiles Folder"
Location = New-Object System.Drawing.Point(136, 2)
Width=73
Height=33
BackColor="LightSkyBlue"
Font = "8pt"
}
$btn_open3.Add_Click({
Invoke-expression $("explorer """ + ${env:temp} + "\cleansew.new""")
})
$panelMysew.Controls.Add($btn_open3)
}
$panel.Controls.Add($panelMysew)
# Add the panel to the form
$form.Controls.Add($panel)
# Create a panel to hold control buttons
$panelB = New-Object System.Windows.Forms.Panel -Property @{
Location = New-Object System.Drawing.Point(1, 53)
Width= 120
Height= 420
Font="Calibri, 15pt"
}
$script:exitmode = $Null
# Create the Edit button
$btn_go = New-Object System.Windows.Forms.Button -Property @{
Text = "Go"
Location = New-Object System.Drawing.Point(4,4)
Width= 100
Height= 30
ForeColor="White"
BackColor="RoyalBlue"
UseVisualStyleBackColor="False"
}
$btn_go.Add_Click({
$script:exitmode = "Go"
$form.Close()
})