# FileSorter.ps1 # Script to process files based on JSON configuration files function Get-DirectoryInput { param ( [string]$Prompt ) while ($true) { $directory = Read-Host -Prompt $Prompt $directory = $directory -replace '"', '' if (Test-Path -Path $directory -PathType Container) { return $directory } else { Write-Host "Please enter a valid directory path." } } } function Get-FilesDictionary { param ( [string]$Path ) $pattern = "(videos|images).*\.json" $files = Get-ChildItem -Path $Path -File | Where-Object { $_.Name -match $pattern } | Sort-Object LastWriteTime $filesDict = @{} foreach ($file in $files) { $jsonContent = Get-Content -Path $file.FullName -Raw | ConvertFrom-Json foreach ($property in $jsonContent.PSObject.Properties) { $filesDict[$property.Name] = $property.Value } } return $filesDict } function Move-Files { param ( [string]$SourceDir, [string]$DestDir, [hashtable]$FilesDict ) if (-not (Test-Path -Path $DestDir -PathType Container)) { New-Item -Path $DestDir -ItemType Directory | Out-Null } $missing = 0 $removed = 0 $moved = 0 foreach ($file in $FilesDict.Keys) { $filePath = Join-Path -Path $SourceDir -ChildPath $file if (-not (Test-Path -Path $filePath -PathType Leaf)) { $missing++ continue } if ($FilesDict[$file]) { Move-Item -Path $filePath -Destination (Join-Path -Path $DestDir -ChildPath $file) $moved++ } else { # Send to Recycle Bin Add-Type -AssemblyName Microsoft.VisualBasic [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($filePath, 'OnlyErrorDialogs', 'SendToRecycleBin') $removed++ } } # Delete the JSON files $pattern = "(videos|images).*\.json" $jsonFiles = Get-ChildItem -Path $SourceDir -File | Where-Object { $_.Name -match $pattern } foreach ($file in $jsonFiles) { Add-Type -AssemblyName Microsoft.VisualBasic [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') } $total = $FilesDict.Count Write-Host "Processed $total files (moved: $moved, removed: $removed, missing: $missing)." Read-Host "Press Enter to continue" } # Main script try { if ($args.Count -gt 0 -and (Test-Path -Path $args[0] -PathType Container)) { $sourcePath = $args[0] } else { $sourcePath = Get-DirectoryInput -Prompt "Input folder" } $jsonPath = Join-Path -Path $env:USERPROFILE -ChildPath "Downloads" $keepDir = Join-Path -Path $sourcePath -ChildPath "Keep" $filesDict = Get-FilesDictionary -Path $jsonPath if ($filesDict.Count -eq 0) { Write-Host "JSON files not found." Read-Host "Press Enter to exit" exit } Move-Files -SourceDir $sourcePath -DestDir $keepDir -FilesDict $filesDict } catch { Write-Error "An error occurred: $_" Read-Host "Press Enter to exit" }