Bläddra i källkod

Fixing bugs in the script to get a running one

Did a complete overall
Seems to be working so far on main scenario
Still needs to be cleaned and might bug out in some cases
master
Figg 1 månad sedan
förälder
incheckning
d51ae3397e
1 ändrade filer med 102 tillägg och 55 borttagningar
  1. 102
    55
      ArrangePictures.ps1

+ 102
- 55
ArrangePictures.ps1 Visa fil

@@ -1,81 +1,128 @@
1
-# Demande à l'utilisateur de saisir les chemins source et destination
2
-$zipFilePath = Read-Host "Veuillez entrer le chemin de l'archive source"
3
-$destinationPath = Read-Host "Veuillez entrer le chemin du dossier destination"
1
+# Fonction pour récupérer une Array des extensions d'images et vidéos depuis un json
2
+function Get-ImageVideoExtensions {
3
+    param (
4
+        [string] $sourceUrl = "https://cdn.jsdelivr.net/gh/jshttp/mime-db@v1.52.0/db.json"
5
+    )
6
+    $jsonData = (Invoke-RestMethod $sourceUrl).PSObject.Properties
7
+    $extensions = @()
4 8
 
5
-# Vérifier si le fichier ZIP existe
6
-if (-Not (Test-Path $zipFilePath)) {
7
-    Write-Host "Le fichier spécifié n'existe pas : $zipFilePath"
8
-    Pause
9
-    exit
10
-}
11
-
12
-# Créer un dossier temporaire pour dézipper l'archive
13
-$tempFolder = Join-Path (Get-Item $zipFilePath).DirectoryName ((Get-Item $zipFilePath).BaseName + "_temp")
14
-
15
-# Dézipper l'archive
16
-Expand-Archive -Path $zipFilePath -DestinationPath $tempFolder
9
+    foreach ($item in $jsonData) {
10
+        if ($item.Name -like "image*" -or $item.Name -like "video*") {
11
+            $extensions += $item.Value.extensions
12
+        }
13
+    }
17 14
 
18
-# Extensions d'images et de vidéos
19
-$imageVideoExtensions = @("jpg", "jpeg", "mp4", "gif")
15
+    $extensions = $extensions | Sort-Object -Unique
16
+    return $extensions
17
+}
20 18
 
21
-# Fonction pour obtenir le MimeType d'un fichier
22
-function Get-MimeType {
23
-    param ($filePath)
24
-    $shell = New-Object -ComObject Shell.Application
25
-    $folder = $shell.Namespace((Get-Item $filePath).DirectoryName)
26
-    $item = $folder.ParseName((Get-Item $filePath).Name)
27
-    $mimeType = $folder.GetDetailsOf($item, 2) # "Type" dans les détails EXIF
28
-    return $mimeType
19
+# Fonction pour décompresser les archives
20
+function Decompress-ArchiveIfNeeded {
21
+    param(
22
+        [string]$ArchivePath,
23
+        [string]$ExtractPath
24
+    )
25
+    
26
+    if (Test-Path $ArchivePath -PathType Leaf) {
27
+        $tempDir = Join-Path -Path $ExtractPath -ChildPath ([System.IO.Path]::GetRandomFileName())
28
+        while (Test-Path $tempDir) {
29
+            $tempDir = Join-Path -Path $ExtractPath -ChildPath ([System.IO.Path]::GetRandomFileName())
30
+        }
31
+        New-Item -Path $tempDir -ItemType Directory | Out-Null
32
+        Expand-Archive -Path $ArchivePath -DestinationPath $tempDir
33
+        return $tempDir
34
+    }
35
+    return $null
29 36
 }
30 37
 
31 38
 # Fonction pour obtenir la date de création d'une image/vidéo
32 39
 function Get-OriginalDate {
33
-    param ($filePath)
34
-    $shell = New-Object -ComObject Shell.Application
35
-    $folder = $shell.Namespace((Get-Item $filePath).DirectoryName)
36
-    $item = $folder.ParseName((Get-Item $filePath).Name)
37
-    $dateTaken = $folder.GetDetailsOf($item, 12) # "Date Taken" dans les détails EXIF
38
-    $dateTaken = [System.Text.RegularExpressions.Regex]::Replace($dateTaken, '[^\x20-\x7E]', '').Trim()
39
-    $parsedDate = $null
40
-    if ([datetime]::TryParse($dateTaken, [ref]$parsedDate)) {
41
-        return $parsedDate
40
+    param (
41
+        $file
42
+    )
43
+    # Tentative de lecture des données EXIF
44
+    $exif = Try { [System.Drawing.Image]::FromFile($file.FullName) } Catch { $null }
45
+
46
+    if ($exif) {
47
+        $exifDate = $exif.PropertyItems | Where-Object { $_.Id -eq 0x9003 } | ForEach-Object {
48
+            [System.Text.Encoding]::ASCII.GetString($_.Value).TrimEnd([char]0)
49
+        }
50
+        if ($exifDate) {
51
+            $date = [datetime]::ParseExact($exifDate, "yyyy:MM:dd HH:mm:ss", $null)
52
+        } else {
53
+            $date = $file.CreationTime
54
+        }
55
+        $exif.Dispose()
42 56
     } else {
43
-        return $null
57
+        $date = $file.CreationTime
44 58
     }
45 59
 }
46 60
 
47
-# Parcourir récursivement le dossier temporaire
48
-Get-ChildItem -Path $tempFolder -Recurse -File | ForEach-Object {
61
+# Demande des paramètres si non fournis
62
+if (-not $args[0] -or -not $args[1]) {
63
+    $SourceDir = Read-Host "Entrez le chemin du dossier source"
64
+    $DestinationDir = Read-Host "Entrez le chemin du dossier destination"
65
+} else {
66
+    $SourceDir = $args[0]
67
+    $DestinationDir = $args[1]
68
+}
69
+
70
+# Vérifie si le dossier source est une archive
71
+if ($SourceDir -match "\.zip$") {
72
+    $SourceDir = Decompress-ArchiveIfNeeded -ArchivePath $SourceDir -ExtractPath $env:TEMP
73
+    if (-not $SourceDir) {
74
+        Write-Host "L'archive n'a pas pu être décompressée."
75
+        return
76
+    }
77
+}
78
+
79
+$validExtensions = Get-ImageVideoExtensions
80
+
81
+# Parcourt tous les fichiers récursivement dans le dossier source
82
+Get-ChildItem -Path $SourceDir -Recurse -File | ForEach-Object {
49 83
     $file = $_
50 84
     $extension = $file.Extension.ToLower().TrimStart('.')
51 85
 
52
-    # Vérifier le MimeType ou l'extension
53
-    $mimeType = Get-MimeType -filePath $file.FullName
54
-    $isImageOrVideo = $mimeType.StartsWith("image/") -or $mimeType.StartsWith("video/") -or $extension -in $imageVideoExtensions
86
+    if ($extension -in $validExtensions) {
87
+        # Tentative de lecture des données EXIF
88
+        $exif = Try { [System.Drawing.Image]::FromFile($file.FullName) } Catch { $null }
55 89
 
56
-    if ($isImageOrVideo) {
57
-        # Obtenir la date de création originale
58
-        $originalDate = Get-OriginalDate -filePath $file.FullName
90
+        if ($exif) {
91
+            $exifDate = $exif.PropertyItems | Where-Object { $_.Id -eq 0x9003 } | ForEach-Object {
92
+                [System.Text.Encoding]::ASCII.GetString($_.Value).TrimEnd([char]0)
93
+            }
94
+            if ($exifDate) {
95
+                $originalDate = [datetime]::ParseExact($exifDate, "yyyy:MM:dd HH:mm:ss", $null)
96
+            } else {
97
+                $originalDate = $file.CreationTime
98
+            }
99
+            $exif.Dispose()
100
+        } else {
101
+            $originalDate = $file.CreationTime
102
+        }
103
+        
59 104
         if (-Not $originalDate) {
60
-            Write-Host "Avertissement : Pas de date de création trouvée pour le fichier $($file.FullName)"
105
+            $targetFolder = Join-Path -Path $DestinationDir -ChildPath "Non daté"
61 106
         } else {
62 107
             # Créer le dossier de destination basé sur l'année et le mois
63 108
             $year = $originalDate.Year
64 109
             $monthNum = $originalDate.Month.ToString("00")
65 110
             $monthName = $originalDate.ToString("MMMM", [System.Globalization.CultureInfo]::GetCultureInfo("fr-FR"))
66
-            $targetFolder = Join-Path -Path $destinationPath -ChildPath "$year\$monthNum - $monthName"
67
-
68
-            if (-Not (Test-Path $targetFolder)) {
69
-                New-Item -Path $targetFolder -ItemType Directory | Out-Null
70
-            }
111
+            $targetFolder = Join-Path -Path $DestinationDir -ChildPath "$year\$monthNum - $monthName"
112
+        }
71 113
 
72
-            # Copier le fichier dans le dossier de destination
73
-            Copy-Item -Path $file.FullName -Destination $targetFolder
114
+        if (-Not (Test-Path $targetFolder)) {
115
+            New-Item -Path $targetFolder -ItemType Directory | Out-Null
74 116
         }
117
+
118
+        # Copier le fichier dans le dossier de destination
119
+        Copy-Item -Path $file.FullName -Destination $targetFolder
120
+    } else {
121
+        Write-Host "Fichier ignoré: $($file.FullName)"
75 122
     }
76 123
 }
77 124
 
78
-# Supprimer le dossier temporaire
79
-Remove-Item -Recurse -Force $tempFolder
80
-Write-Host "Dossier temporaire supprimé : $tempFolder"
81
-Pause
125
+# Suppression du dossier temporaire si nécessaire
126
+if ($SourceDir -like "$env:TEMP\*") {
127
+    Remove-Item -Path $SourceDir -Recurse -Force
128
+}

Laddar…
Avbryt
Spara