| |
|
341
|
Programación / Scripting / [APORTE] [PowerShell] IrfanView | Convert image files to JPG
|
en: 4 Marzo 2024, 14:45 pm
|
El siguiente script desarrollado en PowerShell y dependiente del programa de terceros IrfanView, sirve para convertir todos los archivos de imagen del directorio actual, a formato JPG. En la sección "Variables" dentro del script pueden personalizar la calidad de codificación JPG y los tipos de archivos de imagen a procesar entre otras cosas configurables. 
<# =========================================================================================== | | | Variables | | | =========================================================================================== #> $inputDirectoryPath = "$PSScriptRoot" $fileNameSearchPattern = "*.*" $imageExts = @("avif", "bmp", "jp2", "jpg", "png", "tga", "tif", "webp") $recurse = $false $irfanviewFullPath = "C:\Program Files\IrfanView\i_view64.exe" $jpgQuality = 95 $overwriteConfirm = $true $sendToRecycleBinConvertedFiles = $true <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +===========================================+" Write-Host " | |" Write-Host " | This script will search for image files |" Write-Host " | in the current working directory, and use |" Write-Host " | IrfanView to convert them to JPG format. |" Write-Host " | |" Write-Host " +===========================================+" Write-Host "" Write-Host " Script Settings " -ForegroundColor DarkGray Write-Host " ========================" -ForegroundColor DarkGray Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray Write-Host " Search File Extensions..: $($imageExts -join ', ')" -ForegroundColor DarkGray Write-Host " IrfanView Full Path.....: $irfanviewFullPath" -ForegroundColor DarkGray Write-Host " JPG Quality.............: $jpgQuality%" -ForegroundColor DarkGray Write-Host " Confirm Overwrite JPG...: $overwriteConfirm" -ForegroundColor DarkGray Write-Host " Recycle Converted Files.: $sendToRecycleBinConvertedFiles" -ForegroundColor DarkGray Write-Host "" } function Confirm-Continue { Write-Host " Press 'Y' key to continue or 'N' to exit." Write-Host "" Write-Host " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} } function Validate-Parameters { if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) { Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if (-not (Test-Path -LiteralPath $irfanviewFullPath -PathType Leaf)) { Write-Host " Irfanview file path does not exists!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ($imageExts.Count -eq 0) { Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } } function Convert-Files { Clear-Host Add-Type -AssemblyName Microsoft.VisualBasic $imageFiles = $null if ($recurse) { $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') } } else { $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') } } foreach ($imageFile in $imageFiles) { Write-Host " Converting to JPG: $($imageFile.FullName.Replace($inputDirectoryPath, "."))" $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($imageFile.Name) $outputFilePath = Join-Path -Path ($imageFile.Directory.FullName) -ChildPath "$fileNameWithoutExtension.jpg" if ((Test-Path -LiteralPath $outputFilePath -PathType Leaf) -and ($overwriteConfirm)) { # El archivo no existe o no se debe sobrescribir Write-Warning " Output JPG file already exists but `$overwriteConfirm variable is disabled." Write-Warning " The output JPG file will be overwitten if you continue." Write-Host "" Confirm-Continue Write-Host "" } $exitCode = $null try { $procStartInfo = New-Object System.Diagnostics.ProcessStartInfo $procStartInfo.FileName = $irfanviewFullPath $procStartInfo.Arguments = "`"$($imageFile.FullName)`" /jpgq=$jpgQuality /convert=`"$outputFilePath`"" $procStartInfo.UseShellExecute = $false $process = New-Object System.Diagnostics.Process $process.StartInfo = $procStartInfo $process.Start() | Out-Null $process.WaitForExit() $exitCode = $process.ExitCode } catch { Write-Host "" Write-Host " Error running IrfanView process." -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Error -Message ($_.Exception.Message) Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ($exitCode -eq 0) { Write-Host " File converted successfully." -ForegroundColor DarkGreen if ($sendToRecycleBinConvertedFiles) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($imageFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') Write-Host " File sent to recycle bin." -ForegroundColor DarkGray } Write-Host "" } else { Write-Host " Error converting file to JPG. IrfanView Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red Write-Host "" } } } function Show-GoodbyeScreen { Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Convert image files to JPG - by Elektro" #[System.Console]::SetWindowSize(146, 27) [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Validate-Parameters Confirm-Continue Convert-Files Show-GoodbyeScreen
|
|
|
|
|
342
|
Programación / Scripting / [APORTE] [PowerShell] ImageMagick | Convert image files to ICO
|
en: 4 Marzo 2024, 14:41 pm
|
El siguiente script desarrollado en PowerShell y dependiente del programa de terceros ImageMagick, sirve para convertir todos los archivos de imagen del directorio actual, a formato ICO. Soportando transparencia. En la sección "Variables" dentro del script pueden personalizar los tamaños de las capas del icono, la calidad, y el color usado como transparencia entre otras cosas configurables. 
<# =========================================================================================== | | | Variables | | | =========================================================================================== #> $inputDirectoryPath = "$PSScriptRoot" $recurse = $true $fileSearchExts = @("avif", "bmp", "jp2", "jpg", "jpeg", "png", "tga", "tif", "webp") $fileNameSearchPattern = "*.*" #$fileNameSearchPattern = "Cover.*" $iconSizes = @(256, 128, 96, 64, 48, 32, 24, 16) $iconBackColor = "transparent" $iconQuality = 100 $imageMagickFullPath = "$PSScriptRoot\magick.exe" $imageMagickArgs = @("-define icon:auto-resize=`"$($iconSizes -join ',')`"", "-background $iconBackColor", "-gravity center", "-extent 1:1#", "-quality $iconQuality" ) $overwriteConfirm = $true $sendToRecycleBinConvertedFiles = $false <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +=============================================+" Write-Host " | |" Write-Host " | This script will search for image files |" Write-Host " | in the current working directory, and use |" Write-Host " | ImageMagick to convert them to ICO format. |" Write-Host " | |" Write-Host " +============================================+" Write-Host "" Write-Host " Script Settings " -ForegroundColor DarkGray Write-Host " ========================" -ForegroundColor DarkGray Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray Write-Host " Search File Extensions..: $($fileSearchExts -join ', ')" -ForegroundColor DarkGray Write-Host " ImageMagick Full Path...: $imageMagickFullPath" -ForegroundColor DarkGray Write-Host " Icon Sizes (and order)..: $($iconSizes -join ', ')" -ForegroundColor DarkGray Write-Host " Icon Background Color...: $iconBackColor" -ForegroundColor DarkGray Write-Host " Icon Quality............: $iconQuality" -ForegroundColor DarkGray Write-Host " Confirm Overwrite ICO...: $overwriteConfirm" -ForegroundColor DarkGray Write-Host " Recycle Converted Files.: $sendToRecycleBinConvertedFiles" -ForegroundColor DarkGray # Write-Host " ImageMagick Arguments...: $($imageMagickArgs -join $([Environment]::NewLine) + ' ')" -ForegroundColor DarkGray Write-Host "" } function Confirm-Continue { Write-Host " Press 'Y' key to continue or 'N' to exit." Write-Host "" Write-Host " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} } function Validate-Parameters { if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) { Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if (-not (Test-Path -LiteralPath $imageMagickFullPath -PathType Leaf)) { Write-Host " ImageMagick file path does not exists!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ([string]::IsNullOrEmpty($fileNameSearchPattern)) { Write-Host " `$fileNameSearchPattern variable is null!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ($fileSearchExts.Count -eq 0) { Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } } function Convert-Files { Clear-Host Add-Type -AssemblyName Microsoft.VisualBasic $imageFiles = $null if ($recurse) { $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $fileSearchExts -contains $_.Extension.ToLower().TrimStart('.') } } else { $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $fileSearchExts -contains $_.Extension.ToLower().TrimStart('.') } } foreach ($imageFile in $imageFiles) { Write-Host " Converting to ICO: $($imageFile.FullName.Replace($inputDirectoryPath, "."))" $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($imageFile.Name) $outputFilePath = Join-Path -Path ($imageFile.Directory.FullName) -ChildPath "$fileNameWithoutExtension.ico" if ((Test-Path -LiteralPath $outputFilePath -PathType Leaf) -and ($overwriteConfirm)) { # El archivo no existe o no se debe sobrescribir Write-Warning " Output ICO file already exists but `$overwriteConfirm variable is disabled." Write-Warning " The output ICO file will be overwitten if you continue." Write-Host "" Confirm-Continue Write-Host "" } $exitCode = $null try { $procStartInfo = New-Object System.Diagnostics.ProcessStartInfo $procStartInfo.FileName = $imageMagickFullPath $procStartInfo.Arguments = "`"$($imageFile.FullName)`" $($imageMagickArgs -join ' ') `"$outputFilePath`"" $procStartInfo.UseShellExecute = $false $process = New-Object System.Diagnostics.Process $process.StartInfo = $procStartInfo $process.Start() | Out-Null $process.WaitForExit() $exitCode = $process.ExitCode } catch { Write-Host "" Write-Host " Error running ImageMagick process." -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Error -Message ($_.Exception.Message) Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ($exitCode -eq 0) { Write-Host " File converted successfully." -ForegroundColor DarkGreen if ($sendToRecycleBinConvertedFiles) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($imageFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') Write-Host " File sent to recycle bin." -ForegroundColor DarkGray } Write-Host "" } else { Write-Host " Error converting file to ICO. ImageMagick Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red Write-Host "" } } } function Show-GoodbyeScreen { Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Convert image files to ICO - by Elektro" #[System.Console]::SetWindowSize(146, 27) [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Validate-Parameters Confirm-Continue Convert-Files Show-GoodbyeScreen
|
|
|
|
|
343
|
Programación / Scripting / [APORTE] [BATCH] | Clean nVidia shader cache
|
en: 4 Marzo 2024, 14:30 pm
|
El siguiente Batch-script tiene la función de eliminar los archivos de cache de sombreadores de texturas generados por las tarjetas/drivers de nVidia, lo que puede solucionar fallas o errores gráficos en algunos video juegos, o simplemente lo pueden utilizar para eliminar un poco de espacio usado cuando sea necesario (a veces pueden haber gigabytes de datos de cache de shaders). Funciona para los que tengan instalados drivers recientes, y drivers no tan recientes. 
:SHOW_WELCOME_SCREEN COLOR 07 ECHO:This script will perform a cleanup of the nVidia's shader cache files. ECHO:Removing the shader cache files may fix crashes or graphic errors in some video games. ECHO:Note that shader cache files that are in use cannot be deleted. CHOICE /C "YN" /M "Continue" CLS :DO_WORK REM This directory only exists prior to nVidia drivers v471.11 (IF Exist " %ProgramData%\NVIDIA\NV_Cache\*" (DEL /A /F /Q " %ProgramData%\NVIDIA\NV_Cache\*" )) || (GOTO:SHOW_ERROR_SCREEN ) REM These directories exist beginning with nVidia drivers v471.11 (IF Exist " %LocalAppData%\NVIDIA\DXCache\*" (DEL /A /F /Q " %LocalAppData%\NVIDIA\DXCache\*" )) || (GOTO:SHOW_ERROR_SCREEN ) (IF Exist " %LocalAppData%\NVIDIA\GLCache\*" (DEL /A /F /Q " %LocalAppData%\NVIDIA\GLCache\*" )) || (GOTO:SHOW_ERROR_SCREEN ) :SHOW_GOODBYE_SCREEN COLOR 0A :SHOW_ERROR_SCREEN COLOR 0C ECHO:ERROR DETECTED. THE PROGRAM WILL TERMINATE NOW.
|
|
|
|
|
344
|
Programación / Scripting / Re: [APORTE] [PowerShell] 3rd Party Driver Backup Tool
|
en: 3 Marzo 2024, 23:01 pm
|
muy bien indentado y ordenado el código, bien legible. ¡Que va!, te agradezco los elogios pero con la honestidad y la humildad por delante me veo obligado a hacer un pequeño inciso para abordar tu comentario, ya que precisamente este es el código peor estructurado en comparación con los demás scripts de PowerShell que he compartido estos días. No he aplicado ninguna mecánica de encapsulación o modularidad para dividir el código fuente en partes más pequeñas y autónomas como funciones que realicen tareas específicas, tampoco he añadido lineas separatorias ni documentación o comentarios explicativos al código ...más allá de lo que se imprime en la "pantalla de bienvenida". Es un código que hice rápido (pero sin cometer errores de lógica) y harto de tener que escribir el comando de DISM en la CMD. Al final tantas líneas de código se basan en una simple ejecución "controlada" del proceso DISM (y en la creación automatizada del directorio donde guardar los drivers), por lo que es algo muy simple y no me voy a esmerar más en adornar y estructurar este código. Pero te lo agradezco, de nuevo.
los creas con el idioma inglés y es así como debería ser con un idioma universal y porque tenés la idea y propósito de que tus programas y códigos sean usados en todo el mundo por personas de todos los idiomas. Totalmente de acuerdo. Programar con la intención de compartir tu creación para que (quizás, con suerte) le pueda servir a otras personas, y hacerlo en Español u otros idiomas que no sean el Inglés (y ya ni hablemos de hacerlo en Catalán, Euskera o Gallego), solo sirve para imponerse límites absurdos de comunicación a uno mismo y cerrarse las puertas de la visibilidad a nivel mundial. Y si uno no domina suficientemente el Inglés, al menos debería intentarlo con un traductor online. Aunque el Español es el segundo idioma más hablado del mundo, después del chino. Creo que todavía sigue siendo así. Pero en la práctica todo se transmite en Inglés... Yo a veces me encuentro códigos de programadores asiáticos que claramente han recurrido a usar un traductor como Google Translate para escribir todos los comentarios del código fuente y las cadenas de texto de variables y etc, y la traducción suele ser una porquería, pero sin duda alguna se agradece que estén en Inglés por que medio se entiende todo bien, y si esos códigos estuvieran escritos en chino mandarín probablemente no lograrían captar la atención (o al menos la mía no, desde luego) y por lo tanto no podrían llegar a alcanzar una visibilidad y utilidad a nivel global, por que la mayoría al ver algo escrito en chino simplemente lo acabaríamos ignorando al primer vistazo. Me pasa mucho con los códigos en ruso también. Yo no voy a hacer la labor de traducir algo que el autor no ha traducido al Inglés. Me indigna un poco, lo reconozco xD por que considero que decidir programar en Inglés o hacerlo en Español no se puede reducir a un debate de preferencias personales. Ni siquiera en el ámbito privado. ¡Ni mucho menos que los profesores enseñen a programar en Español!. Pero bueno, esto es solamente mi opinión personal. Entiendo que habrán defensores de la idea de programar en el idioma que a uno le de la gana, de programar con el idioma con el que uno se sienta más a gusto o incluso con el que mejor se identifique, y lo respeto, pero no comparto ese pensamiento. Yo sostengo la idea de que programar basándose en preferencias lingüisticas que sean excluyentes del Inglés, o basándose en identitarismos nacionalistas absurdos (Catalán, Euskera, Gallego, etc) no aporta ni un solo beneficio en la vida real (más allá de que te puedan pedir programar en cierto idioma o dialecto como requisito para trabajar como funcionario en algo relacionado con la programación o la informática en general). ¡Un saludo!.
|
|
|
|
|
345
|
Programación / Scripting / [APORTE] [PowerShell] Truncate Log Files
|
en: 3 Marzo 2024, 22:14 pm
|
El siguiente script desarrollado en PowerShell sirve para truncar el tamaño, a cero bytes, de los archivos log (*.log) dentro del directorio actual y subdirectorios. También se puede usar desde el directorio raiz "C:\", por ejemplo. Es simplemente una herramienta de limpieza ocasional. En herramientas de limpieza como CCleaner se puede especificar una regla para buscar y eliminar archivos log, sin embargo, si el archivo está en uso, este tipo de herramientas no lo podrá eliminar. En cambio, la metodología empleada en este script se beneficiará de cualquier archivo en uso que comparta permisos de escritura para poder borrar su contenido sin llegar a eliminar el archivo en simismo.   <# =========================================================================================== | | | .NET Code | | | =========================================================================================== #> $netCode = @' Option Strict On Option Explicit On Option Infer Off Imports System Imports System.Runtime.InteropServices Imports System.Text Public Class FileUtils Public Shared Function FormatFileSize(fileSize As Long) As String Dim buffer As New StringBuilder(16) NativeMethods.StrFormatByteSize(fileSize, buffer, buffer.MaxCapacity) Return buffer.ToString() End Function End Class Friend NotInheritable Class NativeMethods <DllImport("Shlwapi.dll", CharSet:=CharSet.Auto)> Friend Shared Function StrFormatByteSize(fileSize As Long, <MarshalAs(UnmanagedType.LPTStr)> buffer As StringBuilder, bufferSize As Integer) As Long End Function End Class '@ $netType = Add-Type -TypeDefinition $netCode ` -CodeDomProvider (New-Object Microsoft.VisualBasic.VBCodeProvider) ` -PassThru ` -ReferencedAssemblies "System.dll" ` | where { $_.IsPublic } <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Output "" Write-Output " $($host.ui.RawUI.WindowTitle)" Write-Output " +==========================================================+" Write-Output " | |" Write-Output " | This script will search for log files (*.log) inside the |" Write-Output " | current working directory (including subdirectories) to |" Write-Output " | truncate them by setting their length to zero. |" Write-Output " | |" Write-Output " | This may be useful to help reduce the size of a system |" Write-Output " | full of heavy sized log files. |" Write-Output " | |" Write-Output " +==========================================================+" Write-Output "" } function Confirm-Continue { Write-Output " Press 'Y' key to continue or 'N' to exit." Write-Output "" Write-Output " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} else {Clear-Host} } function Truncate-LogFiles { Write-Output "Fetching log files in ""$($PWD)"", please wait..." Write-Output "" $logFiles = Get-ChildItem -Path $PWD -File -Filter "*.log" -Recurse -Force -ErrorAction SilentlyContinue if (-not $logFiles) { Write-Warning "No log files found in directory: $($PWD)" Return } Clear-Host foreach ($logFile in $logFiles) { if ($logFile.Length -eq 0) { Continue } $formattedFileSize = [FileUtils]::FormatFileSize($logFile.Length) Write-Output "Truncating file: $($LogFile.FullName) ($($formattedFileSize)) ..." try { # [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($logFile.FullName, [Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs, [Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin) $fs = [System.IO.File]::OpenWrite($logFile.FullName) $fs.SetLength(0) $fs.Close() } catch { Write-Host "Access denied to file, it may be in use." -ForegroundColor Yellow } Start-Sleep -MilliSeconds 50 } } function Show-GoodbyeScreen { Write-Output "" Write-Host "Operation Completed." -BackgroundColor Black -ForegroundColor Green Write-Output "" Write-Output "Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Truncate Log Files - by Elektro" [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Confirm-Continue Truncate-LogFiles Show-GoodbyeScreen
|
|
|
|
|
346
|
Programación / Scripting / [APORTE] [PowerShell] Windows Event Logs Cleaner
|
en: 3 Marzo 2024, 21:54 pm
|
El siguiente script desarrollado en el lenguaje Powershell sirve como "atajo" para eliminar todas las entradas de los registros de eventos de Windows (que se pueden analizar mediante la herramienta ubicada en: "C:\Windows\System32\eventvwr.exe"). Nota: esto es algo que también se puede hacer con CCleaner.  
<# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Output "" Write-Output " $($host.ui.RawUI.WindowTitle)" Write-Output " +=================================================+" Write-Output " | |" Write-Output " | This script will clear all the entries from the |" Write-Output " | Windows event logs on the current computer, and |" Write-Output " | display a table with the deletion results. |" Write-Output " | |" Write-Output " +=================================================+" Write-Output "" } function Confirm-Continue { Write-Host " Press 'Y' key to continue or 'N' key to exit." Write-Host "" Write-Host " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} else {Clear-Host} } # https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/clear-eventlog?view=powershell-5.1#example-4-clear-all-logs-on-the-specified-computers-then-display-the-event-log-list function Clear-EventLogs ($computerName=".") { try { $logsBefore = Get-EventLog -ComputerName $computerName -List | Select-Object Log, @{Name="Before";Expression={$_.Entries.Count}} Get-EventLog -ComputerName $computername -List | ForEach-Object {$_.Log} | ForEach-Object { Write-Host "Deleting $_ event logs..." Clear-EventLog -ComputerName $computername -LogName $_ } $logsAfter = Get-EventLog -ComputerName $computerName -List | Select-Object Log, @{Name="After";Expression={$_.Entries.Count}} $logsDiff = $logsBefore | ForEach-Object { $log = $_.Log $Before = $_.Before $After = ($logsAfter | Where-Object {$_.Log -eq $log}).After [PSCustomObject]@{ Log = $log Before = $Before After = $After } } $logsDiff|Format-Table } catch { Write-Host "Something went wrong when calling '$($MyInvocation.MyCommand.Name)' method:" Write-Host "" Write-Warning ($_.Exception.InnerException.Message) Write-Host "" Write-Error -Message ($_.Exception | Format-List * -Force | Out-String) Write-Host "" Write-Host "Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } } function Show-GoodbyeScreen { Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" Write-Host "Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Windows Event Logs Cleaner - by Elektro" [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Confirm-Continue Clear-EventLogs -ComputerName "." Show-GoodbyeScreen Exit(0)
|
|
|
|
|
347
|
Programación / Scripting / [APORTE] [PowerShell] 3rd Party Driver Backup Tool
|
en: 3 Marzo 2024, 21:41 pm
|
El siguiente script desarrollado en el lenguaje Powershell sirve para generar una copia de seguridad de todos los paquetes de drivers de terceros que tengamos instalados en el sistema operativo. Para ello simplemente se utiliza el programa DISM en segundo plano.    
Import-Module Microsoft.PowerShell.Management [System.Console]::Title = "3rd Party Driver Backup Tool - by Elektro" [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } $Timestamp = Get-Date -Format "yyyy∕MMMM∕dd HH꞉mm꞉ss" $OutputDirectory = "$env:USERPROFILE\Desktop\3rd Party Drivers Backup $Timestamp" Do { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +===========================================================+" Write-Host " | |" Write-Host " | This script will make a full backup of the 3rd party |" Write-Host " | device drivers that are installed in the current machine, |" Write-Host " | and will save them into the user's desktop directory. |" Write-Host " | |" Write-Host " +===========================================================+" Write-Host "" Write-Host " CURRENT SCRIPT CONFIG:" Write-Host " ----------------------" Write-Host "" Write-Host " Output Directory:" Write-Host " $OutputDirectory" Write-Host " ___________________________________________________________" Write-Host "" Write-Host " -Continue? (Y/N)" $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} else {Clear-Host} if (-not (Test-Path $OutputDirectory)) { New-Item -Path "$OutputDirectory" -ItemType "Directory" -Force | Out-Null } & { $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = "DISM.exe" $psi.Arguments = "/Online /Export-Driver /Destination:""$OutputDirectory""" $psi.UseShellExecute = $false $p = [System.Diagnostics.Process]::Start($psi) $p.WaitForExit() $dismExitCode = $p.ExitCode if ($dismExitCode -eq 0) { Write-Host "" Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" } else { Write-Host "" Write-Host "Operation Failed. Confirm to delete the output directory:" -BackgroundColor Black -ForegroundColor Red Write-Host "" Remove-Item -Path "$OutputDirectory" -Recurse -Force -ErrorAction SilentlyContinue -Confirm:$true } } Write-Host "" Write-Host "Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit($dismExitCode)
|
|
|
|
|
349
|
Programación / Scripting / [APORTE] [PowerShell] RAR.exe | Multi-Compression Test Tool (Para Archivos)
|
en: 2 Marzo 2024, 13:01 pm
|
El siguiente script desarrollado en PowerShell y dependiente del programa externo RAR.exe (WinRAR), sirve para comprimir cada archivo dentro del directorio actual de forma individual, con compresión máxima, y utilizando los tamaños de diccionario especificados. La sección "Variables" dentro del script permite configurar varias cosas, entre ellas: - Los tamaños de diccionario. - Las extensiones de archivo que se deben procesar sin aplicar compresión. - Preservar solamente el archivo RAR generado con el menor tamaño de todos. (eliminar los archivos RAR de mayor tamaño) - Especificar una diferencia de tamaño (tolerancia) arbitraria para eliminar archivos RAR generados (con mayores tamaños de diccionario) de un tamaño de archivo similar. - Enviar los archivos RAR eliminados a la papelera de reciclaje. Es muy útil, por ejemplo, para comprimir de forma automatizada archivos ISO de consolas, y obtener así el mejor resultado entre Tamaño de diccionario / Tamaño de archivo.
 
<# =========================================================================================== | | | Variables | | | =========================================================================================== #> $rarExecutablePath = "C:\Program Files\WinRAR\rar.exe" $dictionarySizes = @(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048) $toleranceSizeDiff = "1MB" $keepOnlySmallestRarFile = $true $sendRarFilesToRecycleBin = $false $compressedFileTypesArchive = @( "7z" , "arc", "bz2" , "bzip", "bzip2", "gz" , "gz2", "gza" , "gzi" , "gzip" , "lha", "lz" , "lz4" , "lzh" , "lzma" , "rar", "sfx", "tgz" , "tlz" , "tlzma", "uha", "zip", "zipx", "zpaq" ) $compressedFileTypesAudio = @( "aac", "ac3", "fla","flac", "m4a", "mp3", "ogg", "ogm", "usm", "wma" ) $compressedFileTypesVideo = @( "asf", "avc", "avi" , "bik" , "bk2" , "f4v" , "flv" , "m1v", "m2t", "m2ts", "m2v" , "m4v" , "mpv4", "mkv", "mov", "mp4" , "mpeg", "mpg" , "mts" , "qt" , "ts" , "vob" , "vp6" , "webm", "wmv" ) $compressedFileTypesOther = @( "avif", "jpeg", "jpg" , "gif" , "pdf", "pam" , "paq6", "paq7", "paq8", "par" , "par2", "wad" ) [string]$fileTypesToKeepUncompressed = ( $compressedFileTypesArchive + $compressedFileTypesAudio + $compressedFileTypesVideo + $compressedFileTypesOther ) -join ';' <# =========================================================================================== | | | rar.exe commands (only those used in this script) | | | =========================================================================================== <Commands> a Add files to archive <Switches> -am[s,r] Archive name and time [save, restore] -c- Disable comments show -cfg- Ignore configuration file and RAR environment variable. -dh Open shared files -ep1 Exclude base directory from names -ht[b|c] Select hash type [BLAKE2,CRC32] for file checksum -id[c,d,n,p,q] Display or disable messages -ilog[name] Log errors to file -isnd[-] Control notification sounds -m<0..5> Set compression level (0-store...3-default...5-maximal) -ma[4|5] Specify a version of archiving format -md<n>[k,m,g] Dictionary size in KB, MB or GB -ms[list] Specify file types to store. -o[+|-] Set the overwrite mode -oc Set NTFS Compressed attribute. -oh Save hard links as the link instead of the file -oi[0-4][:min] Save identical files as references -ol[a] Process symbolic links as the link [absolute paths] -oni Allow potentially incompatible names -qo[-|+] Add quick open information [none|force] -r Recurse subdirectories -ri<P>[:<S>] Set priority (0-default,1-min..15-max) and sleep time in ms -s- Disable solid archiving -t Test files after archiving -tk Keep original archive time -tl Set archive time to newest file -ts[m,c,a,p] Save or restore time (modification, creation, access, preserve) -u Update files -w<path> Assign work directory #> <# =========================================================================================== | | | .NET Code | | | =========================================================================================== #> Add-Type -TypeDefinition @" using System; using System.Runtime.InteropServices; public class Win32Functions { [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)] public static extern long StrFormatByteSizeW(long fileSize, System.Text.StringBuilder buffer, int bufferSize); } "@ <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +========================================================+" Write-Host " | |" Write-Host " | This script will use RAR.exe to compress each file in |" Write-Host " | the current working directory individually, each using |" Write-Host " | different dictionary sizes, with max. compression, |" Write-Host " | generating this way multiple RAR files for evaluating |" Write-Host " | compression rates on these dictionary sizes. |" Write-Host " | |" Write-Host " +=========================================================+" Write-Host "" Write-Host " Script Settings " -ForegroundColor DarkGray Write-Host " ===========================" -ForegroundColor DarkGray Write-Host " RAR Executable Path: $([System.IO.Path]::GetFullPath($rarExecutablePath))" -ForegroundColor Gray Write-Host "" -ForegroundColor DarkGray Write-Host " Dictionary Sizes (Megabyte): $($dictionarySizes -join ', ')" -ForegroundColor Gray Write-Host " The script will create a RAR archive for each specified dictionary size." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " File Types To Keep Uncompressed: `$keepCompressedFileTypesUncompressed" -ForegroundColor Gray Write-Host " The script will instruct RAR to don't compress the specified known compressed file types." -ForegroundColor DarkGray Write-Host " (See `$keepCompressedFileTypesUncompressed variable definition to manage the file types)" -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Tolerance File Size Difference: $toleranceSizeDiff" -ForegroundColor Gray Write-Host " Any newly created RAR file whose file size compared to previously " -ForegroundColor DarkGray Write-Host " created RAR files is within the specified tolerance value, it will be deleted." -ForegroundColor DarkGray Write-Host " For example, if `$toleranceSizeDiff value is 1MB:" -ForegroundColor DarkGray Write-Host " If a created RAR file of 32 MB dict. size has a file size of 100 MB," -ForegroundColor DarkGray Write-Host " and then a newly created RAR file of 64 MB dict. size has a file size of 99 MB, " -ForegroundColor DarkGray Write-Host " the RAR file of 64 MB dict. size will be deleted because it only differs in 1MB or less." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Keep only smallest rar file: $keepOnlySmallestRarFile" -ForegroundColor Gray Write-Host " If True, the script will delete any newly created RAR file " -ForegroundColor DarkGray Write-Host " whose file size is bigger than previously created RAR files." -ForegroundColor DarkGray Write-Host " Note: it takes into account the specified `$toleranceSizeDiff value." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Send RAR files to recycle bin: $sendRarFilesToRecycleBin" -ForegroundColor Gray Write-Host " If True, the script will send RAR files to recycle bin instead of permanently deleting them." -ForegroundColor DarkGray Write-Host "" } function Confirm-Continue { Write-Host " Press 'Y' key to continue or 'N' to exit." Write-Host "" Write-Host " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} else {Clear-Host} } function Compress-Files { Add-Type -AssemblyName Microsoft.VisualBasic $dictionarySizes = $dictionarySizes | Sort-Object # Partir y formatear la cadena de file types para acomodarlo a la linea de argumentos de rar.exe if (-not [String]::IsNullOrEmpty($fileTypesToKeepUncompressed)) { $fileTypeTokens = $fileTypesToKeepUncompressed -split ';' $fileTypesArgumentLines = @() for ($i = 0; $i -lt $fileTypeTokens.Count; $i += 20) { $fileTypesArgumentLines += "-ms" + ($fileTypeTokens[$i..($i + 19)] -join ';') + [Environment]::NewLine } if ($fileTypesArgumentLines.Count -gt 0) { $fileTypesArgumentLines[-1] = $fileTypesArgumentLines[-1] -replace [Environment]::NewLine, '' } } else { $fileTypesArgumentLines = "-ms " } foreach ($inputFile in Get-ChildItem -LiteralPath "$PSScriptRoot" -File) { if ($inputFile.Name -eq [System.IO.Path]::GetFileName($PSCommandPath)) { continue } # Keeps track of created rar files by rar.exe $createdRarFiles = New-Object System.Collections.Generic.List[System.IO.FileInfo] foreach ($size in $dictionarySizes) { if (($size -ne $dictionarySizes[0]) -and ($inputFile.Length * 4) -le ($size * 1MB)) { $formattedSize = Format-FileSize -fileSize $inputFile.Length Write-Host "Ignoring compression with too big dictionary size of $size mb for a $formattedSize file: `"$($inputFile.Name)`"..." -ForegroundColor Yellow continue } $outputRarFilePath = "$($inputFile.FullName)_$($size)mb.rar" $errorLogFilePath = "$($inputFile.FullName)_$($size)mb_error.log" $arguments = @( " a -u -ams -c- -cfg- -dh -ep1 -htb -idcdn -isnd- -iver -m5 -ma5 -md$($size)m", " -o+ -oc -oh -oi2 -ol -oni -qo+ -r -ri0:0 -s- -t -tk -tl -tsmca+", " $fileTypesArgumentLines", " -x`"*\$($MyInvocation.MyCommand.Name)`"", " -w`"$($env:TEMP)`"", " -ilog`"$errorLogFilePath`"", " -- `"$outputRarFilePath`"", " -- `"$($inputFile.FullName)`"" ) Write-Host "Compressing file with $size mb dictionary dize: `"$($inputFile.Name)`"..." #Write-Host "" #Write-Host "rar.exe arguments:" -ForegroundColor DarkGray #Write-Host ($arguments -join [Environment]::NewLine) -ForegroundColor DarkGray $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $rarExecutablePath $psi.Arguments = $arguments -join ' ' $psi.RedirectStandardOutput = $false $psi.UseShellExecute = $false $psi.CreateNoWindow = $false $process = [System.Diagnostics.Process]::Start($psi) $process.WaitForExit() $outputRarFile = New-Object System.IO.FileInfo($outputRarFilePath) $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length Write-Host "" Write-Host "Created rar with file name: $($outputRarFile.Name) ($formattedOutputRarFileSize)" -ForegroundColor DarkGreen if ($toleranceSizeDiff -ne $null) { if ($createdRarFiles.Count -ne 0) { $outputRarFileMB = [Math]::Floor($outputRarFile.Length / $toleranceSizeDiff) $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length foreach ($rarFile in $createdRarFiles) { if ($rarFile.Exists) { $sizeMB = [Math]::Floor($rarFile.Length / $toleranceSizeDiff) $formattedRarFileSize = Format-FileSize -fileSize $rarFile.Length if ($outputRarFileMB -eq $sizeMB) { Write-Host "" Write-Host "File size of this created RAR file ($formattedOutputRarFileSize) is within the $toleranceSizeDiff tolerance difference" -ForegroundColor DarkGray Write-Host "than a previously created RAR file ($formattedRarFileSize) with smaller dictionary size..." -ForegroundColor DarkGray Write-Host "Deleting file: `"$($outputRarFile.Name)`" ($formattedOutputRarFileSize)..." -ForegroundColor Yellow if ($sendRarFilesToRecycleBin) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') } else { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'DeletePermanently') } Write-Host "Deletion completed." -ForegroundColor Yellow } } } } } if (Test-Path -LiteralPath $outputRarFile.FullName -PathType Leaf) { $createdRarFiles.Add($outputRarFile) } Write-Host "" } if ($keepOnlySmallestRarFile -and $createdRarFiles.Count -gt 0) { $existingFiles = $createdRarFiles | Where-Object { $_.Exists } if ($existingFiles.Count -gt 0) { Write-Host "`$keepOnlySmallestRarFile variable is `$True. Comparing file sizes of created RAR files..." -ForegroundColor Yellow Write-Host "" $smallestFile = $existingFiles | Sort-Object Length | Select-Object -First 1 foreach ($file in $existingFiles) { if ($file -ne $smallestFile) { $formattedFileSize = Format-FileSize -fileSize $file.Length Write-Host "Deleting file: `"$($file.Name)`" ($formattedFileSize)..." -ForegroundColor Yellow if ($sendRarFilesToRecycleBin) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') } else { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'DeletePermanently') } Write-Host "Deletion completed." -ForegroundColor Yellow Write-Host "" } } $formattedSmallestFileSize = Format-FileSize -fileSize $smallestFile.Length Write-Host "Smallest file kept: $($smallestFile.Name) ($formattedSmallestFileSize)" -ForegroundColor Green Write-Host "" } } } } function Format-FileSize { param( [long]$fileSize ) $buffer = New-Object System.Text.StringBuilder 260 [Win32Functions]::StrFormatByteSizeW($fileSize, $buffer, $buffer.Capacity) | Out-Null return $buffer.ToString() } function Show-GoodbyeScreen { Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" Write-Host "Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "RAR Multi-Compression Test Tool (Files) - by Elektro" #[System.Console]::SetWindowSize(150, 45) [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Confirm-Continue Compress-Files Show-GoodbyeScreen
|
|
|
|
|
350
|
Programación / Scripting / [APORTE] [PowerShell] RAR.exe | Multi-Compression Test Tool (Para Directorios)
|
en: 2 Marzo 2024, 12:47 pm
|
El siguiente script desarrollado en PowerShell y dependiente del programa externo RAR.exe (WinRAR), sirve para comprimir cada directorio dentro del directorio actual de forma individual, con compresión máxima, y utilizando los tamaños de diccionario especificados. La sección "Variables" dentro del script permite configurar varias cosas, entre ellas: - Los tamaños de diccionario. - Las extensiones de archivo que se deben procesar sin aplicar compresión. - Preservar solamente el archivo RAR generado con el menor tamaño de todos. (eliminar los archivos RAR de mayor tamaño) - Especificar una diferencia de tamaño (tolerancia) arbitraria para eliminar archivos RAR generados (con mayores tamaños de diccionario) de un tamaño de archivo similar. - Enviar los archivos RAR eliminados a la papelera de reciclaje. Es muy útil, por ejemplo, para comprimir de forma automatizada directorios de video juegos para PC y obtener así el mejor resultado entre Tamaño de diccionario / Tamaño de archivo.
  
<# =========================================================================================== | | | Variables | | | =========================================================================================== #> $rarExecutablePath = "C:\Program Files\WinRAR\rar.exe" $dictionarySizes = @(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048) $toleranceSizeDiff = "1MB" $keepOnlySmallestRarFile = $true $sendRarFilesToRecycleBin = $false $compressedFileTypesArchive = @( "7z" , "arc", "bz2" , "bzip", "bzip2", "gz" , "gz2", "gza" , "gzi" , "gzip" , "lha", "lz" , "lz4" , "lzh" , "lzma" , "rar", "sfx", "tgz" , "tlz" , "tlzma", "uha", "zip", "zipx", "zpaq" ) $compressedFileTypesAudio = @( "aac", "ac3", "fla","flac", "m4a", "mp3", "ogg", "ogm", "usm", "wma" ) $compressedFileTypesVideo = @( "asf", "avc", "avi" , "bik" , "bk2" , "f4v" , "flv" , "m1v", "m2t", "m2ts", "m2v" , "m4v" , "mpv4", "mkv", "mov", "mp4" , "mpeg", "mpg" , "mts" , "qt" , "ts" , "vob" , "vp6" , "webm", "wmv" ) $compressedFileTypesOther = @( "avif", "jpeg", "jpg" , "gif" , "pdf", "pam" , "paq6", "paq7", "paq8", "par" , "par2", "wad" ) [string]$fileTypesToKeepUncompressed = ( $compressedFileTypesArchive + $compressedFileTypesAudio + $compressedFileTypesVideo + $compressedFileTypesOther ) -join ';' <# =========================================================================================== | | | rar.exe commands (only those used in this script) | | | =========================================================================================== <Commands> a Add files to archive <Switches> -am[s,r] Archive name and time [save, restore] -c- Disable comments show -cfg- Ignore configuration file and RAR environment variable. -dh Open shared files -ep1 Exclude base directory from names -ht[b|c] Select hash type [BLAKE2,CRC32] for file checksum -id[c,d,n,p,q] Display or disable messages -ilog[name] Log errors to file -isnd[-] Control notification sounds -m<0..5> Set compression level (0-store...3-default...5-maximal) -ma[4|5] Specify a version of archiving format -md<n>[k,m,g] Dictionary size in KB, MB or GB -ms[list] Specify file types to store. -o[+|-] Set the overwrite mode -oc Set NTFS Compressed attribute. -oh Save hard links as the link instead of the file -oi[0-4][:min] Save identical files as references -ol[a] Process symbolic links as the link [absolute paths] -oni Allow potentially incompatible names -qo[-|+] Add quick open information [none|force] -r Recurse subdirectories -ri<P>[:<S>] Set priority (0-default,1-min..15-max) and sleep time in ms -s- Disable solid archiving -t Test files after archiving -tk Keep original archive time -tl Set archive time to newest file -ts[m,c,a,p] Save or restore time (modification, creation, access, preserve) -u Update files -w<path> Assign work directory #> <# =========================================================================================== | | | .NET Code | | | =========================================================================================== #> Add-Type -TypeDefinition @" using System; using System.Runtime.InteropServices; public class Win32Functions { [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)] public static extern long StrFormatByteSizeW(long fileSize, System.Text.StringBuilder buffer, int bufferSize); } "@ <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +==========================================================+" Write-Host " | |" Write-Host " | This script will use RAR.exe to compress each directory |" Write-Host " | in the current working directory individually, each |" Write-Host " | using different dictionary sizes, with max. compression, |" Write-Host " | generating this way multiple RAR files for evaluating |" Write-Host " | compression rates on these dictionary sizes. |" Write-Host " | |" Write-Host " +==========================================================+" Write-Host "" Write-Host " Script Settings " -ForegroundColor DarkGray Write-Host " ===========================" -ForegroundColor DarkGray Write-Host " RAR Executable Path: $([System.IO.Path]::GetFullPath($rarExecutablePath))" -ForegroundColor Gray Write-Host "" -ForegroundColor DarkGray Write-Host " Dictionary Sizes (Megabyte): $($dictionarySizes -join ', ')" -ForegroundColor Gray Write-Host " The script will create a RAR archive for each specified dictionary size." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " File Types To Keep Uncompressed: `$keepCompressedFileTypesUncompressed" -ForegroundColor Gray Write-Host " The script will instruct RAR to don't compress the specified known compressed file types." -ForegroundColor DarkGray Write-Host " (See `$keepCompressedFileTypesUncompressed variable definition to manage the file types)" -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Tolerance File Size Difference: $toleranceSizeDiff" -ForegroundColor Gray Write-Host " Any newly created RAR file whose file size compared to previously " -ForegroundColor DarkGray Write-Host " created RAR files is within the specified tolerance value, it will be deleted." -ForegroundColor DarkGray Write-Host " For example, if `$toleranceSizeDiff value is 1MB:" -ForegroundColor DarkGray Write-Host " If a created RAR file of 32 MB dict. size has a file size of 100 MB," -ForegroundColor DarkGray Write-Host " and then a newly created RAR file of 64 MB dict. size has a file size of 99 MB, " -ForegroundColor DarkGray Write-Host " the RAR file of 64 MB dict. size will be deleted because it only differs in 1MB or less." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Keep only smallest rar file: $keepOnlySmallestRarFile" -ForegroundColor Gray Write-Host " If True, the script will delete any newly created RAR file " -ForegroundColor DarkGray Write-Host " whose file size is bigger than previously created RAR files." -ForegroundColor DarkGray Write-Host " Note: it takes into account the specified `$toleranceSizeDiff value." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Send RAR files to recycle bin: $sendRarFilesToRecycleBin" -ForegroundColor Gray Write-Host " If True, the script will send RAR files to recycle bin instead of permanently deleting them." -ForegroundColor DarkGray Write-Host "" } function Confirm-Continue { Write-Host " Press 'Y' key to continue or 'N' to exit." Write-Host "" Write-Host " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} else {Clear-Host} } function Compress-Files { Add-Type -AssemblyName Microsoft.VisualBasic $dictionarySizes = $dictionarySizes | Sort-Object # Partir y formatear la cadena de file types para acomodarlo a la linea de argumentos de rar.exe if (-not [String]::IsNullOrEmpty($fileTypesToKeepUncompressed)) { $fileTypeTokens = $fileTypesToKeepUncompressed -split ';' $fileTypesArgumentLines = @() for ($i = 0; $i -lt $fileTypeTokens.Count; $i += 20) { $fileTypesArgumentLines += "-ms" + ($fileTypeTokens[$i..($i + 19)] -join ';') + [Environment]::NewLine } if ($fileTypesArgumentLines.Count -gt 0) { $fileTypesArgumentLines[-1] = $fileTypesArgumentLines[-1] -replace [Environment]::NewLine, '' } } else { $fileTypesArgumentLines = "-ms " } foreach ($dir in Get-ChildItem -LiteralPath "$PSScriptRoot" -Directory) { $dirSizeBytes = (Get-ChildItem -LiteralPath "$($dir.FullName)" -Recurse | Measure-Object -Property Length -sum).Sum # Keeps track of created rar files by rar.exe $createdRarFiles = New-Object System.Collections.Generic.List[System.IO.FileInfo] foreach ($size in $dictionarySizes) { if (($size -ne $dictionarySizes[0]) -and ($dirSizeBytes * 4) -le ($size * 1MB)) { $formattedDirSize = Format-FileSize -fileSize $dirSizeBytes Write-Host "Ignoring compression with too big dictionary size of $size mb for a $formattedDirSize directory: `"$($dir.FullName)`"..." -ForegroundColor Yellow continue } $outputRarFilePath = "$($dir.FullName)_$($size)mb.rar" $errorLogFilePath = "$($dir.FullName)_$($size)mb_error.log" $arguments = @( " a -u -ams -c- -cfg- -dh -ep1 -htb -idcdn -isnd- -iver -m5 -ma5 -md$($size)m", " -o+ -oc -oh -oi2 -ol -oni -qo+ -r -ri0:0 -s- -t -tk -tl -tsmca+", " $fileTypesArgumentLines", " -x`"*\$($MyInvocation.MyCommand.Name)`"", " -w`"$($env:TEMP)`"", " -ilog`"$errorLogFilePath`"", " -- `"$outputRarFilePath`"", " -- `"$($dir.FullName)\*`"" ) Write-Host "Compressing directory with $size mb dictionary dize: `"$($dir.Name)`"..." #Write-Host "" #Write-Host "rar.exe arguments:" -ForegroundColor DarkGray #Write-Host ($arguments -join [Environment]::NewLine) -ForegroundColor DarkGray $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $rarExecutablePath $psi.Arguments = $arguments -join ' ' $psi.RedirectStandardOutput = $false $psi.UseShellExecute = $false $psi.CreateNoWindow = $false $process = [System.Diagnostics.Process]::Start($psi) $process.WaitForExit() $outputRarFile = New-Object System.IO.FileInfo($outputRarFilePath) $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length Write-Host "" Write-Host "Created rar with file name: $($outputRarFile.Name) ($formattedOutputRarFileSize)" -ForegroundColor DarkGreen if ($toleranceSizeDiff -ne $null) { if ($createdRarFiles.Count -ne 0) { $outputRarFileMB = [Math]::Floor($outputRarFile.Length / $toleranceSizeDiff) $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length foreach ($rarFile in $createdRarFiles) { if ($rarFile.Exists) { $sizeMB = [Math]::Floor($rarFile.Length / $toleranceSizeDiff) $formattedRarFileSize = Format-FileSize -fileSize $rarFile.Length if ($outputRarFileMB -eq $sizeMB) { Write-Host "" Write-Host "File size of this created RAR file ($formattedOutputRarFileSize) is within the $toleranceSizeDiff tolerance difference" -ForegroundColor DarkGray Write-Host "than a previously created RAR file ($formattedRarFileSize) with smaller dictionary size..." -ForegroundColor DarkGray Write-Host "Deleting file: `"$($outputRarFile.Name)`" ($formattedOutputRarFileSize)..." -ForegroundColor Yellow if ($sendRarFilesToRecycleBin) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') } else { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'DeletePermanently') } Write-Host "Deletion completed." -ForegroundColor Yellow } } } } } if (Test-Path -LiteralPath $outputRarFile.FullName -PathType Leaf) { $createdRarFiles.Add($outputRarFile) } Write-Host "" } if ($keepOnlySmallestRarFile -and $createdRarFiles.Count -gt 0) { $existingFiles = $createdRarFiles | Where-Object { $_.Exists } if ($existingFiles.Count -gt 0) { Write-Host "`$keepOnlySmallestRarFile variable is `$True. Comparing file sizes of created RAR files..." -ForegroundColor Yellow Write-Host "" $smallestFile = $existingFiles | Sort-Object Length | Select-Object -First 1 foreach ($file in $existingFiles) { if ($file -ne $smallestFile) { $formattedFileSize = Format-FileSize -fileSize $file.Length Write-Host "Deleting file: `"$($file.Name)`" ($formattedFileSize)..." -ForegroundColor Yellow if ($sendRarFilesToRecycleBin) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') } else { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'DeletePermanently') } Write-Host "Deletion completed." -ForegroundColor Yellow Write-Host "" } } $formattedSmallestFileSize = Format-FileSize -fileSize $smallestFile.Length Write-Host "Smallest file kept: $($smallestFile.Name) ($formattedSmallestFileSize)" -ForegroundColor Green Write-Host "" } } } } function Format-FileSize { param( [long]$fileSize ) $buffer = New-Object System.Text.StringBuilder 260 [Win32Functions]::StrFormatByteSizeW($fileSize, $buffer, $buffer.Capacity) | Out-Null return $buffer.ToString() } function Show-GoodbyeScreen { Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" Write-Host "Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "RAR Multi-Compression Test Tool (Directories) - by Elektro" #[System.Console]::SetWindowSize(150, 45) [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Confirm-Continue Compress-Files Show-GoodbyeScreen
|
|
|
|
|
|
| |
|