-
Notifications
You must be signed in to change notification settings - Fork 0
/
EmbroideryCollection-Cleanup.ps1
2900 lines (2553 loc) · 115 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 - Mar 2024
#>
param
(
[Parameter(Mandatory = $false)]
[int32]$DownloadDaysOld = 7, # How many days old show it scan for Zip files in Download
[int32]$SetSize = 10,
[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]$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
)
$ECCVERSION = "v0.6.8"
# $VerbosePreference = "Continue"
# $InformationPreference = "Continue"
<# ******** CONFIGURATION ********#>
$preferredSewType = 'vp4', 'vp3', 'pes', 'pcs','hus','dst'
$alltypes = 'hus', 'dst', 'exp', 'jef', 'pes', 'vip', 'vp3', 'xxx', 'sew', 'vp4', 'pcs', 'vf3', 'csd', 'zsk', 'emd' , 'ese', 'phc', 'art', 'ofm', 'shv', 'pxf', 'svg', 'dxf', 'pec', 'pcm', 'pxf', 'dem', 'phc', 'mhv', 'bmc', "jpx", "jef+"
$foldupDir = 'images', 'sewing helps', 'Designs', 'Design Files', 'brother-babylock-pes', 'janome-jef', 'singer-xxx', 'husqvarna-viking-hus', 'commercial formats - dst-exp', 'artista-art'
$goodInstructionTypes = ('pdf','doc', 'docx', 'txt','rtf', 'mp4', 'ppt', 'pptx', 'gif', 'jpg', 'png', 'bmp','mov', 'wmv', 'avi','mpg', 'm4v', 'htm', 'html' )
$TandCs = @('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"="";
"DownloadDaysOld" = "Age of 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'
}
$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'
}
$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-host " ".padright(15) "Embroidery Collection Cleanup version: $ECCVERSION on PS $($PSVersionTable.PSVersion.major).$($PSVersionTable.PSVersion.minor)".padright(70) -ForegroundColor White -BackgroundColor Blue
$RemovePrefix = ($PSVersionTable.PSVersion.Major -lt 7 )
$filecnt = 0
$script:sizecnt = 0
$Script:dircnt = 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
$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/"
$missingSewnetAddin = ((get-itemproperty -path "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.vp3\ShellEx\{e357fccd-a995-4576-b01f-234630154e96}").'(default)' -ne "{370F9E36-A651-4BB3-89A9-A6DB957C63CC}")
#
# 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
}
# 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 CloudFile {
# Class properties
[string] $Cloudid
[string] $FileName
CloudFile() { $this.Init(@{}) }
# Convenience constructor from hashtable
CloudFile([hashtable]$Properties) { $this.Init($Properties) }
# Common constructor for id and FileName
CloudFile([string]$Cloudid, [string]$FileName) {
$this.Init(@{Cloudid = $Cloudid; File = $FileName })
}
# Shared initializer method
[void] Init([hashtable]$Properties) {
foreach ($Property in $Properties.Keys) {
$this.$Property = $Properties.$Property
}
}
# Method to return a string representation of the file
[string] ToString() {
return "$($this.CloudId) by $($this.FileName)"
}
}
class SewingFile {
# Class properties
[String] $NameIndexed # could be file or file.txt
[String] $Name # File.txt
[String] $Base # File
[String] $DirectoryName # C:\Dir\
[String] $Hash # hash value of the file calculated when we need it
[String] $FullName # C:\Dir\File.txt
[System.IO.FileInfo] $FileInfo
[System.DateTime] $LastWriteTime
[int32] $Priority
[String] $RelPath
[String] $CloudRef
[String] $Push
[System.IO.FileInfo] $TmpPath
[System.IO.FileInfo] $KeepPath
# Default constructor
SewingFile() { $this.Init(@{}) }
# Convenience constructor from hashtable
SewingFile([hashtable]$Properties) { $this.Init($Properties) }
# Common constructor for id and FileName
SewingFile([string]$Cloudid, [string]$FileName) {
$this.Init(@{Cloudid = $Cloudid; File = $FileName })
}
# Shared initializer method
[void] Init([hashtable]$Properties) {
foreach ($Property in $Properties.Keys) {
$this.$Property = $Properties.$Property
}
}
# Method to return a string representation of the file
[string] ToString() {
return "$($this.relpath + $this.Name)"
}
[string] MoveFile() {
if ($this.TmpPath) {
copy-item -Path $this.TmpPath.FullName -Destination $this.FileInfo.FullName
$this.TmpPath = $null
} elseif ($this.KeepPath) {
copy-item -Path $this.KeepPath.FullName -Destination $this.FileInfo.FullName
$this.KeepPath = $null
} else {
# Nothing to move
return ""
}
return $this.FileInfo.FullName
}
}
class SewingFileList {
# Static property to hold the list of SewingFiles
static [System.Collections.Generic.List[SewingFile]] $SewingFiles
# Static method to initialize the list of SewingFiles. Called in the other
# static methods to avoid needing to explicit initialize the value.
static [void] Initialize() { [SewingFileList]::Initialize($false) }
static [bool] Initialize([bool]$force) {
if ([SewingFileList]::SewingFiles.Count -gt 0 -and -not $force) {
return $false
}
[SewingFileList]::SewingFiles = [System.Collections.Generic.List[SewingFile]]::new()
return $true
}
# Ensure a SewingFile is valid for the list.
static [void] Validate([SewingFile]$SewingFile) {
$Prefix = @(
'SewingFile validation failed: SewingFile must be defined with the NameIndexed,'
'FullName, and LastWriteTime properties, but'
) -join ' '
if ($null -eq $SewingFile) { throw "$Prefix was null" }
if ([string]::IsNullOrEmpty($SewingFile.NameIndexed)) {
throw "$Prefix NameIndexed wasn't defined"
}
if ([string]::IsNullOrEmpty($SewingFile.FullName)) {
throw "$Prefix FullName wasn't defined"
}
if ([datetime]::MinValue -eq $SewingFile.LastWriteTime) {
throw "$Prefix LastWriteTime wasn't defined"
}
}
# Static methods to manage the list of SewingFiles.
# Add a SewingFile if it's not already in the list.
static [void] Add([SewingFile]$SewingFile) {
[SewingFileList]::Initialize()
[SewingFileList]::Validate($SewingFile)
if ([SewingFileList]::SewingFiles.Contains($SewingFile)) {
throw "SewingFile '$SewingFile' already in list"
}
$FindPredicate = {
param([SewingFile]$s)
$s.NameIndexed -eq $SewingFile.NameIndexed -and
$s.AutFullNamehor -eq $SewingFile.FullName -and
$s.LastWriteTime -eq $SewingFile.LastWriteTime
}.GetNewClosure()
if ([SewingFileList]::SewingFiles.Find($FindPredicate)) {
throw "SewingFile '$SewingFile' already in list"
}
[SewingFileList]::SewingFiles.Add($SewingFile)
}
# Clear the list of SewingFiles.
static [void] Clear() {
[SewingFileList]::Initialize()
[SewingFileList]::SewingFiles.Clear()
}
# Find a specific SewingFile using a filtering scriptblock.
static [SewingFile] Find([scriptblock]$Predicate) {
[SewingFileList]::Initialize()
return [SewingFileList]::SewingFiles.Find($Predicate)
}
# Find every SewingFile matching the filtering scriptblock.
static [SewingFile[]] FindAll([scriptblock]$Predicate) {
[SewingFileList]::Initialize()
return [SewingFileList]::SewingFiles.FindAll($Predicate)
}
# Remove a specific SewingFile.
static [void] Remove([SewingFile]$SewingFile) {
[SewingFileList]::Initialize()
[SewingFileList]::SewingFiles.Remove($SewingFile)
}
# Remove a SewingFile by property value.
static [void] RemoveBy([string]$Property, [string]$Value) {
[SewingFileList]::Initialize()
$Index = [SewingFileList]::SewingFiles.FindIndex({
param($b)
$b.$Property -eq $Value
}.GetNewClosure())
if ($Index -ge 0) {
[SewingFileList]::SewingFiles.RemoveAt($Index)
}
}
}
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
}
if ($missingSewnetAddin) {
$DragUpload = $true
}
$CloudAuthAvailable = $false
if ($CloudAPI) {
$DragUpload = $false
$ShowExample = $false
$CloudAuthAvailable = ((Get-Module -Name PSAuthClient).count -gt 0)
if (-not $CloudAuthAvailable) {
Write-Progress -Activity "Checking for Authenication Module"
if ((Get-Module -ListAvailable | Where-Object { $_.Name -eq "PSAuthClient" }).count -gt 0) {
Import-Module PSAuthClient
$CloudAuthAvailable = ((Get-Module -Name PSAuthClient).count -gt 0)
}
else {
write-host "-- Please wait while the script installs missing module --" -foreground Yellow -NoNewline
Install-Module -name PSAuthClient -scope:CurrentUser
Import-Module PSAuthClient
$CloudAuthAvailable = ((Get-Module -Name PSAuthClient).count -gt 0)
write-host "Completed" -foreground Yellow
}
Write-Progress -Completed $true
}
}
$doit = !$Testing
# This is for development testing and debugging
if ($env:COMPUTERNAME -eq "DESKTOP-R3PSDBU_") { # -and $Testing) {
$docsdir = "d:\Users\kjeff\"
$downloaddir = "d:\Users\kjeff\downloads"
$doit = $true
}
#=============================================================================================
function LogAction($File, $Action, [Boolean]$isInstructions = $false) {
$now = Get-Date -Format "yyyy/MMM/dd HH:mm "
$extra = (&{if ($isInstructions) { " Instructions"} else { "Embroidery" } })
write-verbose "$Action $File type: $extra"
Add-Content -Path $LogFile -Value ("$now$Action $File $extra")
}
Function ShowProgress ([string]$Area, [string]$stat = $null)
{
$Script:p++
if ($stat) {
Write-Progress -PercentComplete ($Script:p % 100 ) $Area -Status $stat
} else {
Write-Progress -PercentComplete ($Script:p % 100 ) $Area
}
}
# Delete or recycle a file (full path required)
Function RecycleFile {
param (
[System.IO.FileInfo[]]$file,
[boolean]$purge )
if (!($file)) {
write-warning 'Recycle blank name'
return
}
#BUG-FIX? Long File name detection
$thisfile = get-item $file
if ($thisfile.attributes.hasflag([IO.FileAttributes]'Readonly')) {
$thisfile.attributes -= 'Readonly'
}
try {
if ($purge) {
if ($RemovePrefix) {
Remove-Item -Path "\\?\$($file.FullName)" # Handled by WhatIf
} else {
Remove-Item -Path $file.FullName # Handled by WhatIf
}
} elseif ($doit) {
$shell.NameSpace(17).ParseName($file).InvokeVerb('delete')
}
} catch {
write-warning "Problem deleting: $file - $($file.Fullname)"
}
}
function MyPause {
param (
[string]$Message,
[bool]$Choice = $false,
[string]$BoxMsg,
[int]$Timeout = 0,
[bool]$useGUI = $false,
[bool]$ChoiceDefault = $true
)
$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 }
$x = if ($Choice) {
[System.Windows.Forms.MessageBox]::Show($BoxMsg, 'Cleanup Collection Folders', 'YesNo', 'Question')
} else {
[System.Windows.Forms.MessageBox]::Show($Message)
}
$yes = ($x -eq 'Yes')
} else {
$secondsRunning = 0
if ($Timeout -gt 0) {
Start-Sleep -Milliseconds 100
$host.ui.RawUI.FlushInputBuffer()
}
if ($choice) {
if (!$Message.contains('?')) {
$Message += "?"
}
$yesno = (&{if ($ChoiceDefault) { " (Y/n) " } else { " (y/N) " }})
} else {
$yesno = ""
}
write-progress -Completed $true
Write-Host ($Message + $yesno ) -ForegroundColor Yellow -NoNewline
while (-not $Host.UI.RawUI.KeyAvailable -and $secondsRunning++ -lt $Timeout) {
[Threading.Thread]::Sleep(1000)
}
if ($Host.UI.RawUI.KeyAvailable -or $Timeout -eq 0) {
$needakey = $true
while ($needakey) {
$keystroke = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$yes = 'Yy'.Contains($keystroke.Character)
# Look for yes or no keystrokes
if ($choice) {
$needakey = -not ('YyNn'.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
}
}
}
if ($choice) {
$selectchoice = (&{if ($yes) { "Yes"} else { "No" } })
write-host $selectchoice
} else {
Write-Host " "
}
}
return $yes
}
function GetKeystroke ($choices) {
Start-Sleep -Milliseconds 100
$host.ui.RawUI.FlushInputBuffer()
Write-Host $Message " ($choies)" -ForegroundColor White
$key
do {
$getkey = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$getkey = $getkey.Character.tostring().tolower()
}
while ($choices.tolower().notcontains($getkey))
return $getkey
}
function Test-ExistsOnPath {
param (
[string]$FileName
)
$found = $false
$env:Path.Split([System.IO.Path]::PathSeparator) | where-object {$_ -ne ""} | ForEach-Object {
$fullPath = Join-Path $_ $FileName
if (Test-Path $fullPath -PathType Leaf) {
$found = $true
}
}
return $found
}
# return the relative path of existing folders and files relative to a root path with the prefix of .\
function RelativeDirectory {
param (
[string]$Path,
[string]$rootPath
)
Push-Location -path $rootPath
$relative = Resolve-Path -Path $path -Relative
$relative = $relative.trim("\.\\")
Pop-Location
return $relative
}
# Look within the directory and find files of the same name and return that list
function DuplicateFiles($Path) {
# Initialize an empty list to store the file objects
$FileList = @()
$sp = 0
$Excludes = ($allTypesStar + $TandCs )
ShowProgress "Get file list for duplicate files in different directories ...."
# Get all the files in the directory and sub-directories recursively
$Files = Get-ChildItem -Path $Path -Recurse -include $Excludes -File
# Group the files by their name and extension
ShowProgress "Sorting for duplicate files in different directories .... Please wait"
$FileGroups = $Files | Group-Object -Property Length | Where-Object count -gt 1
ShowProgress "Checking for duplicate files in different directories by name"
$FileGroups = $FileGroups.Group | Group-Object -Property Name | where-object count -gt 1
ShowProgress "Checking for duplicate files in different directories now by hash... this will take time... Please wait"
$FileGroups = $FileGroups.Group | Group-Object -Property {(get-filehash $_.FullName -Algorithm md5).Hash } | where-object count -gt 1
$FileGroups.Group | group-object -property Name | Out-GridView -Title "Additional instances of these files will be removed - as the are exact duplicates"
# Loop through each group of files
foreach ($FileGroup in $FileGroups) {
# If the group has more than one file, it means there are duplicates
# Sort the files by their directory depth, ascending
$SortedFiles = $FileGroup.Group | Sort-Object -Property @{Expression = {$_.FullName.Split('\').Count}}
# Loop through the rest of the files in the group, starting from the second one
foreach ($File in $SortedFiles[1..($SortedFiles.Count - 1)]) {
# Compare the file hashes of the first file and the current file
# Add the current file's System.IO.FileInfo object to the list of duplicates
$FileList += $File
}
}
# Return the list of duplicate files
return $FileList
}
# Look within the directory and find files where the basename is the same as another instance and return that list based on the preference types
function DuplicateFileNames($Path, $ExtensionsOrder = @()) {
# Initialize an empty list to store the file objects
$FileList = @()
$sp = 0
# Get all the files in the directory and sub-directories recursively
$Files = Get-ChildItem -Path $Path -Recurse -File
# If the preferred extensions list is not empty, check for duplicate names with different extensions
if ($ExtensionsOrder.Count -gt 0) {
# Group the files by their base name (without extension)
ShowProgress "Sorting for unneeded formats .... Please wait"
$NameGroups = $Files | Group-Object -Property BaseName,LastWriteTime.date
# Loop through each group of files
foreach ($NameGroup in $NameGroups) {
if (($sp++ % 20) -eq 0) {
ShowProgress "Checking for unneeded formats"
}
# If the group has more than one file, it means there are duplicates
if ($NameGroup.Count -gt 1) {
# Sort the files by their extension, using the preferred extensions list as the order
$SortedFiles = $NameGroup.Group | Sort-Object -Property @{Expression = {(&{if ($ExtensionsOrder.IndexOf($_.Extension) -ne -1) { $ExtensionsOrder.IndexOf($_.Extension) } else {100} })}; Descending = $false}
# Loop through the rest of the files in the group, starting from the second one
foreach ($File in $SortedFiles[1..($SortedFiles.Count - 1)]) {
# Add the current file's System.IO.FileInfo object to the list of duplicates
$FileList += $File
}
}
}
$Files | Sort-Object -Property @{Expression = {(&{if ($ExtensionsOrder.IndexOf($_.Extension) -ne -1) { $ExtensionsOrder.IndexOf($_.Extension) } else {100} })}; Descending = $false} | Group-Object -Property BaseName | where-object count -gt 1 | Out-GridView -Title "Additional instances of these files will be removed - first instances is kept additional are removed"
}
# Return the list of duplicate named files with different types
return $FileList
}
<#
.SYNOPSIS
Checks for files to remove and optionally deletes them.
.DESCRIPTION
This function checks a collection of files and prompts the user to remove them.
It can either move the files to the recycle bin or delete them permanently.
.PARAMETER RemoveFiles
An array of FileInfo objects representing the files to be checked and potentially removed.
.PARAMETER HardDelete
A switch parameter that, when set, will cause files to be deleted permanently instead of being recycled.
.EXAMPLE
$filesToRemove = Get-ChildItem -Path "C:\Temp\*" -File
CheckAndRemove -RemoveFiles $filesToRemove -DeleteWithoutRecycle $true -why "are duplicates"
This example will check all files in C:\Temp and prompt the user to remove them.
.INPUTS
System.IO.FileInfo[]
.OUTPUTS
None
#>
function CheckAndRemove {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[System.IO.FileInfo[]]$RemoveFiles,
[boolean]$DeleteWithoutRecycle,
[string]$why
)
$fcr = $RemoveFiles.length
if ($fcr -gt 0) {
write-host "Found $fcr files that $why and should be removed" -ForegroundColor Yellow
# $RemoveFiles|Select-Object Name, FullName, DirectoryName, Extension | Out-GridView -Title "Files that will be removed - $why (Close this Windows to continue)"
$cont = MyPause 'Remove those files? (No to keep them)' -Choice $true -BoxMsg 'Click Yes to remove them' -ChoiceDefault $false
if ($cont) {
if (!$DeleteWithoutRecycle -and $fcr -gt 100) {
$cont = (MyPause 'This is going to take a while as it moves the files to recycle. Would you like to Delete the file without being able to recover them?' $true 'Click Yes to for a quick delete with NO Recyle!')
if ($cont) {
$DeleteWithoutRecycle = $true
Write-Host "Switching to Fast quick delete without recycle" -ForegroundColor Yellow
}
}
$howDeleted = if ($HardDelete) { 'Deleting ' } else { 'Recycling ' }
$fcs = 0
ForEach ($f in $RemoveFiles) {
RecycleFile -file $f.FullName -purge $DeleteWithoutRecycle
LogAction -File $f.Name -Action "--Remove-file"
if ($fcs % 10 -eq 0) {
ShowProgress ($howDeleted + "extra files from cache") "$fcs of $fcr - $($f.Name)"
}
$fcs++
}
}
if ($fcs) {
write-progress -Activity "Updating Lists of removed files .... Please wait"
$script:mysewingfiles = $mysewingfiles |where-object {$_.FullName -notin ($RemoveFiles.FullName)}
write-progress -Completed $true
}
}
}
# Define a recursive function to traverse directories
Function TailRecursion {
param (
[string]$Path,
[int]$Depth = 0
)
$IsFound = $false
# Recursively call the function for each child directory
Get-ChildItem -Force -LiteralPath $Path -Directory | ForEach-Object {
TailRecursion -Path $_.FullName -Depth ($Depth + 1) | Out-Null
}
# Check if the current directory is empty
$IsEmpty = -not (Get-ChildItem -Force -LiteralPath $Path)
# If the directory is empty and it's not the top directory, remove it
if ($IsEmpty -and $Depth -gt 0) {
Write-Verbose "Removing empty folder: '$Path'"
RecycleFile -file $Path -purge $HardDelete
$IsFound = $true
$Script:DirCount++
ShowProgress "Removing Directory" $Path
LogAction -File $Path -Action "--Remove-Empty-Directory"
}
return $IsFound
}
#-----------------------------------------------------------------------
# Only clear/reset the New files Directory once and only if there are new files with this run
# Let's becareful that we are not clearing the wrong directory
function ChecktoClearNewFilesDirectory {
if ($Script:clearNewFiles) {
if ((get-volume -filePath $NewFilesDir).DriveType -eq "Fixed") {
write-progress -Activity "Preparing working directory"
Get-ChildItem -Path $("\\?\" + $NewFilesDir) -Recurse | Remove-Item -Force -Recurse
write-verbose "CLEARED Copy File Space"
write-progress -Completed $true
}
$Script:clearNewFiles = $false
}
}
<#
function to convert characters which are not found in ASCII; such as á, é, í, ó, ú; into something acceptable such as a, e, i, o, u.
#>
function Remove-Diacritics
{
Param([string]$Text)
$chars = $Text.Normalize([System.Text.NormalizationForm]::FormD).GetEnumerator().Where{
[System.Char]::GetUnicodeCategory($_) -ne [System.Globalization.UnicodeCategory]::NonSpacingMark
}
(-join $chars).Normalize([System.Text.NormalizationForm]::FormC)
}
function FetchImageFile ([string]$source, [string]$destination) {
if (-not (Test-Path $source)) {
Write-Host "[+] Downloading file from '$source'"
try {
(New-Object System.Net.WebClient).DownloadFile($source, $destination)
} catch {
Write-Host "`t[!] Failed to download '$source'"
Write-Host "`t[!] $_"
}
} else {
Write-Verbose "[+] Using existing file."
}
}
function Get-LatestGitHubTag {
param (
[string]$RepositoryOwner,
[string]$RepositoryName
)
# Construct the GitHub API URL for releases
$apiUrl = "https://api.github.com/repos/$RepositoryOwner/$RepositoryName/releases"
Write-Progress -Activity "Checking for script updates..."
try {
# Fetch the releases using Invoke-RestMethod
$releases = Invoke-RestMethod -Uri $apiUrl
# Filter the releases to get the latest one
$latestRelease = $releases | Sort-Object -Property created_at -Descending | Select-Object -First 1
# Extract and return the tag name
$latestRelease = $latestRelease.tag_name
}
catch {
Write-Verbose "Error fetching releases from GitHub: $_"
$latestRelease = ""
}
Write-Progress -Completed $true
return $latestRelease
}
Function OpenForUpload {
if ($CloudAPI -or $UsingUSBDrive) {
return
}
Write-Host "-----------------------------------------------------------------------------------------" -ForegroundColor Green
if ($DragUpload) {
Write-Host "Opening File Explorer & MySewnet Web page" -ForegroundColor Green
Write-Host " ** on MySewNet web page choose 'Upload' and Select all files in Explorer and " -ForegroundColor Green
Write-Host " drag/drop the files a maximum of 5 at a time into the upload box" -ForegroundColor Green
} else {
if ((Get-WmiObject -class Win32_OperatingSystem).Caption -match "Windows 11") {
$wtype = "W11"
Write-Host "Opening File Explorer (using mysewnet add-in)" -ForegroundColor Green
Write-Host " *** Select all files *right-click* and choose 'Show more Options' -> choose 'MySewNet' -> 'Send'" -ForegroundColor Green
} else {
# Assume it is Windows 10 with add-in
$wtype = "W10"
Write-Host "Opening File Explorer (using mysewnet add-in)" -ForegroundColor Green
Write-Host " *** Select all files *right-click* and choose 'MySewNet' -> 'Send'" -ForegroundColor Green
}
}
$firstfile = $(get-childitem -path $NewFilesDir -File -depth 1)
if ($firstfile.count -gt 0) {
$firstfile = $firstfile[0].FullName
$explorercmd = "explorer '/select,""$firstfile""'"
}
else {
Write-Host " There are NO Files to upload" -ForegroundColor Yellow
$firstfile = $NewFilesDir + "\."
$explorercmd = "explorer '$NewFilesDir'"
}
Write-Host "-----------------------------------------------------------------------------------------" -ForegroundColor Green
if ($DragUpload) {
Start-Process $opencloudpage
}
Invoke-expression $explorercmd
if (-not $DragUpload -and $ShowExample) {
$file = Join-Path -path $(Split-Path -path $PSCommandPath) -ChildPath 'HowToSend-w10.gif'
FetchImageFile $file "https://raw.githubusercontent.com/D-Jeffrey/Embroidery-File-Organize/docs/images/main/HowToSend-$wtype.gif"
if (test-path $file) {
write-host "Opening Example (Close it by clicking on the 'X' in the top right corner)"
Add-Type -AssemblyName 'System.Windows.Forms'
$file = (get-item $file)
$img = [System.Drawing.Image]::Fromfile((get-item $file))
[System.Windows.Forms.Application]::EnableVisualStyles()
$form = new-object Windows.Forms.Form
$form.Text = "How to Do it"
$form.Width = $img.Size.Width;
$form.Height = $img.Size.Height;
$pictureBox = new-object Windows.Forms.PictureBox
$pictureBox.Width = $img.Size.Width;
$pictureBox.Height = $img.Size.Height;
$pictureBox.Image = $img;
$form.controls.add($pictureBox)
$form.Add_Shown( { $form.Activate() } )
$form.ShowDialog()
$form.Close()
} else {
write-host "Error: Could not find example file : $file" -foregroundcolor red
}
}
}
#=======================================================================
# Cloud API MySewnet interface reversed by Darren Jeffrey
#=======================================================================
<#
.SYNOPSIS
This function logs into the SewnetCloud.
.DESCRIPTION
The LoginSewnetCloud function sends a POST request to the SewnetCloud API to authenticate a user.
It takes a username and password as parameters, and if the authentication is successful, it stores the session token in a global variable.
.EXAMPLE
LoginSewnetCloud
.OUTPUTS
Boolean. Returns $true if the login is successful, $false otherwise.
.NOTES
The function sets the global variable $Global:sewAuthorizeToken to the session token if the login is successful.
#>
function LoginSewnetCloud
{
$authorization_endpoint = "https://auth.singer.com/authorize"
$token_endpoint = "https://auth.singer.com/oauth/token"
$idparams = @{
Client_Id="rEJOLIIM2rpa155BupM4MxantCGqDc7o"
scope="openid profile email offline_access"
Redirect_Uri="https://mysewnet.com/my-account/login"
customParameters = @{
audience="https://api.mysewnet.com/"
ui_locales="en"
}
}
if ($Global:sewAuthorizeToken -and $Global:expires_on -gt (get-date) ) {
ShowProgress "Using previous MySewNet Logon"
} else {
ShowProgress "Logginning onto MySewNet"
try {
$code = Invoke-OAuth2AuthorizationEndpoint -uri $authorization_endpoint @idparams
} catch {
write-progress -Completed $true
return $false
}
ShowProgress "Authenicating onto MySewNet"
$tokens = Invoke-OAuth2TokenEndpoint -uri $token_endpoint @code
ShowProgress "Completed Logon to MySewNet"
$Global:sewAuthorizeToken = $tokens.access_token
if ($null -eq $tokens.access_token) {
Write-error "Authentication Failed"
return $false
}
$Global:expires_on = (get-date).AddSeconds($tokens.expires_in)
Set-Content -Path $(Join-Path -Path $PSScriptRoot -childpath "Token.txt") $(($Global:expires_on.DateTime | ConvertTo-Json) + ($tokens | ConvertTo-Json))
}
return $true
}
<#
.SYNOPSIS
This function generates authorization header values.
.DESCRIPTION
The authHeaderValues function returns a hashtable of HTTP headers for authorization.
It uses the global variable $Global:sewAuthorizeToken to set the "Authorization" header.
.EXAMPLE
$headers = authHeaderValues
.OUTPUTS
Hashtable. Returns a hashtable of HTTP headers for authorization.
.NOTES
The function uses the global variable $Global:sewAuthorizeToken to set the "Authorization" header.
#>
function authHeaderValues ()
{
return @{
"Accept"="application/json, text/plain, */*"
"Accept-Encoding"="gzip, deflate, br, zstd"
"Accept-Language"="en-US,en;q=0.9"
"Authorization" = "Bearer " + $Global:sewAuthorizeToken
"Origin"="https://www.mysewnet.com"
"Referer"="https://www.mysewnet.com/"
"Host"="api.mysewnet.com"
"Pragma"= "no-cache"
"Cache-Control"="no-cache"
"User-Agent"="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0 EmbroideryCollection Manager Cleanup $ECCVERSION"
}
}
<#
.SYNOPSIS
This function reads metadata from the SewnetCloud.
.DESCRIPTION
The ReadCloudMeta function sends a GET request to the SewnetCloud API to retrieve metadata.
It uses the authHeaderValues function to get the authorization headers.
If the request fails, it retries up to 3 times before giving up.
.EXAMPLE
$metadata = ReadCloudMeta