Инструменты пользователя

Инструменты сайта


projects:windows

Это старая версия документа!


Проекты для Windows

PowerShell скрипт для сортировки по расширениям

$configPath = "SortConfig.ini"
 
# Функция загрузки конфигурации из INI с поддержкой игнорирования файлов
function Load-Config {
    param ($configPath)
 
    if (!(Test-Path $configPath)) {
        @"
[Extensions]
Images = .jpg, .jpeg, .png, .gif, .bmp, .tiff, .webp, .ico, .psd
Documents = .pdf, .doc, .docx, .txt, .xls, .xlsx, .ppt, .pptx, .rtf, .csv
Archives = .zip, .rar, .7z, .tar, .gz, .bz2, .xz, .iso
Videos = .mp4, .mkv, .avi, .mov, .wmv, .flv, .webm
Music = .mp3, .wav, .flac, .aac, .ogg, .m4a, .wma
Torrents = .torrent
Software = .exe, .msi, .iso, .img, .bin, .dmg
Code = .py, .js, .html, .css, .php, .java, .c, .cpp, .cs, .go, .rb, .ts, .sh, .bat, .ps1
3DModels = .obj, .fbx, .stl, .blend, .3ds, .dae, .gltf
VectorGraphics = .svg, .ai, .eps, .cdr
Notes = .md, .rst
System = .ini, .cfg, .reg, .log, .cmd
Books = .epub, .mobi, .djvu
Other =
 
[Logging]
EnableLogging = false
LogFilePath = SortFiles.log
 
[IgnoreFiles]
Files = folder.ico, desktop.ini
"@ | Out-File -Encoding UTF8 $configPath
    }
 
    $config = @{Extensions=@{}; Logging=@{}; IgnoreFiles=@()}
    $currentSection = ""
    foreach ($line in Get-Content $configPath) {
        $line = $line.Trim()
        if ($line -match "^\[(.*?)\]") {
            $currentSection = $matches[1]
        } elseif ($line -match "^(.+?)\s*=\s*(.*)") {
            $key, $value = $matches[1,2]
            if ($currentSection -eq "Extensions") {
                $config.Extensions[$key] = $value -split ",\s*"
            } elseif ($currentSection -eq "Logging") {
                $config.Logging[$key] = $value
            } elseif ($currentSection -eq "IgnoreFiles" -and $key -eq "Files") {
                $config.IgnoreFiles = $value -split ",\s*"
            }
        }
    }
    return $config
}
 
$config = Load-Config $configPath
$fileCategories = $config.Extensions
$ignoredFiles = @($config.IgnoreFiles)
if (!$ignoredFiles) { $ignoredFiles = @() }
 
$enableLogging = $false
if ($config.Logging["EnableLogging"] -match "^(?i)true|1$") {
    $enableLogging = $true
}
$logFilePath = $config.Logging["LogFilePath"]
 
function Write-Log {
    param ($message)
    if ($enableLogging -and $logFilePath) {
        $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        "$timestamp - $message" | Out-File -Append -Encoding UTF8 $logFilePath
    }
}
 
# Определяем папку для сортировки с подтверждением
if ($args.Count -gt 0 -and (Test-Path -PathType Container $args[0])) {
    $TargetFolder = $args[0]
    Add-Type -AssemblyName System.Windows.Forms
    $confirmation = [System.Windows.Forms.MessageBox]::Show("Выбранный каталог: $TargetFolder", "Подтверждение", [System.Windows.Forms.MessageBoxButtons]::OKCancel, [System.Windows.Forms.MessageBoxIcon]::Information)
    if ($confirmation -ne [System.Windows.Forms.DialogResult]::OK) {
        Write-Host "Операция отменена пользователем."
        exit
    }
} else {
    Add-Type -AssemblyName System.Windows.Forms
    $folderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
    $folderBrowser.Description = "Выберите папку для сортировки файлов"
    if ($folderBrowser.ShowDialog() -eq "OK") {
        $confirmation = [System.Windows.Forms.MessageBox]::Show("Выбранный каталог: $($folderBrowser.SelectedPath)", "Подтверждение", [System.Windows.Forms.MessageBoxButtons]::OKCancel, [System.Windows.Forms.MessageBoxIcon]::Information)
        if ($confirmation -ne [System.Windows.Forms.DialogResult]::OK) {
            Write-Host "Операция отменена пользователем."
            exit
        }
        $TargetFolder = $folderBrowser.SelectedPath
    } else {
        Write-Host "Операция отменена пользователем."
        exit
    }
}
 
Write-Host "Выбранная папка: $TargetFolder"
Write-Log "Начало сортировки в папке: $TargetFolder"
 
# Функция сортировки файлов с правильной нумерацией дубликатов
function Sort-Files {
    param ($TargetFolder, $fileCategories, $ignoredFiles)
 
    Get-ChildItem -Path $TargetFolder -File | ForEach-Object {
        if ($ignoredFiles -contains $_.Name) {
            Write-Log "Игнорируем файл: $($_.Name)"
            return
        }
 
        $file = $_
        $destination = $fileCategories.Keys | Where-Object { $file.Extension -in $fileCategories[$_] } | Select-Object -First 1
        if (-not $destination) { $destination = "Other" }
 
        $destPath = Join-Path $TargetFolder $destination
        if (!(Test-Path $destPath)) { New-Item -Path $destPath -ItemType Directory | Out-Null }
 
        $baseName = $file.BaseName -replace " \(Copy \d+\)$", ""
        $extension = $file.Extension
        $newPath = Join-Path $destPath "$baseName$extension"
        $counter = 1
 
        while (Test-Path $newPath) {
            $newPath = Join-Path $destPath "$baseName (Copy $counter)$extension"
            $counter++
        }
 
        try {
            Move-Item -Path $file.FullName -Destination $newPath -ErrorAction Stop
            Write-Log "Перемещён $($file.Name) в $destination как $newPath"
        }
        catch {
            Write-Log "Ошибка перемещения файла: $($file.Name) - $_"
        }
    }
}
 
Sort-Files -TargetFolder $TargetFolder -fileCategories $fileCategories -ignoredFiles $ignoredFiles
projects/windows.1742763188.txt.gz · Последнее изменение: 2025/03/23 23:53 —

Если не указано иное, содержимое этой вики предоставляется на условиях следующей лицензии: CC Attribution 4.0 International
CC Attribution 4.0 International Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki