elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Trabajando con las ramas de git (tercera parte)


  Mostrar Mensajes
Páginas: 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 ... 1236
111  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.





Código
  1. @ECHO OFF
  2.  
  3. CALL:SHOW_WELCOME_SCREEN
  4. CALL:DO_WORK
  5. CALL:SHOW_GOODBYE_SCREEN
  6.  
  7. :SHOW_WELCOME_SCREEN
  8. COLOR 07
  9. ECHO:This script will perform a cleanup of the nVidia's shader cache files.
  10. ECHO:Removing the shader cache files may fix crashes or graphic errors in some video games.
  11. ECHO:Note that shader cache files that are in use cannot be deleted.
  12. CHOICE /C "YN" /M "Continue"
  13. IF "%ERRORLEVEL%" EQU "2" (EXIT 1)
  14. CLS
  15. GOTO:EOF
  16.  
  17. :DO_WORK
  18. REM This directory only exists prior to nVidia drivers v471.11
  19. (IF Exist "%ProgramData%\NVIDIA\NV_Cache\*" (DEL /A /F /Q "%ProgramData%\NVIDIA\NV_Cache\*")) || (GOTO:SHOW_ERROR_SCREEN)
  20. REM These directories exist beginning with nVidia drivers v471.11
  21. (IF Exist "%LocalAppData%\NVIDIA\DXCache\*" (DEL /A /F /Q "%LocalAppData%\NVIDIA\DXCache\*")) || (GOTO:SHOW_ERROR_SCREEN)
  22. (IF Exist "%LocalAppData%\NVIDIA\GLCache\*" (DEL /A /F /Q "%LocalAppData%\NVIDIA\GLCache\*")) || (GOTO:SHOW_ERROR_SCREEN)
  23. GOTO:EOF
  24.  
  25. :SHOW_GOODBYE_SCREEN
  26. COLOR 0A
  27. ECHO:Finished.
  28.  
  29. :SHOW_ERROR_SCREEN
  30. COLOR 0C
  31. ECHO:ERROR DETECTED. THE PROGRAM WILL TERMINATE NOW.
112  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!.
113  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.





Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                    .NET Code                                            |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $netCode = @'
  10.    Option Strict On
  11.    Option Explicit On
  12.    Option Infer Off
  13.  
  14.    Imports System
  15.    Imports System.Runtime.InteropServices
  16.    Imports System.Text
  17.  
  18.    Public Class FileUtils
  19.  
  20.        Public Shared Function FormatFileSize(fileSize As Long) As String
  21.            Dim buffer As New StringBuilder(16)
  22.            NativeMethods.StrFormatByteSize(fileSize, buffer, buffer.MaxCapacity)
  23.            Return buffer.ToString()
  24.        End Function
  25.  
  26.    End Class
  27.  
  28.    Friend NotInheritable Class NativeMethods
  29.  
  30.        <DllImport("Shlwapi.dll", CharSet:=CharSet.Auto)>
  31.        Friend Shared Function StrFormatByteSize(fileSize As Long,
  32.               <MarshalAs(UnmanagedType.LPTStr)> buffer As StringBuilder,
  33.                                                 bufferSize As Integer) As Long
  34.        End Function
  35.  
  36.    End Class
  37. '@
  38.  
  39. $netType = Add-Type -TypeDefinition $netCode `
  40.                    -CodeDomProvider (New-Object Microsoft.VisualBasic.VBCodeProvider) `
  41.                    -PassThru `
  42.                    -ReferencedAssemblies "System.dll" `
  43.                                          | where { $_.IsPublic }
  44.  
  45. <#
  46. ===========================================================================================
  47. |                                                                                         |
  48. |                                    Functions                                            |
  49. |                                                                                         |
  50. ===========================================================================================
  51. #>
  52.  
  53. function Show-WelcomeScreen {
  54.    Clear-Host
  55.    Write-Output ""
  56.    Write-Output " $($host.ui.RawUI.WindowTitle)"
  57.    Write-Output " +==========================================================+"
  58.    Write-Output " |                                                          |"
  59.    Write-Output " | This script will search for log files (*.log) inside the |"
  60.    Write-Output " | current working directory (including subdirectories) to  |"
  61.    Write-Output " | truncate them by setting their length to zero.           |"
  62.    Write-Output " |                                                          |"
  63.    Write-Output " | This may be useful to help reduce the size of a system   |"
  64.    Write-Output " | full of heavy sized log files.                           |"
  65.    Write-Output " |                                                          |"
  66.    Write-Output " +==========================================================+"
  67.    Write-Output ""
  68. }
  69.  
  70. function Confirm-Continue {
  71.    Write-Output " Press 'Y' key to continue or 'N' to exit."
  72.    Write-Output ""
  73.    Write-Output " -Continue? (Y/N)"
  74.    do {
  75.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  76.        $char = $key.Character.ToString().ToUpper()
  77.        if ($char -ne "Y" -and $char -ne "N") {
  78.            [console]::beep(1500, 500)
  79.        }
  80.    } while ($char -ne "Y" -and $char -ne "N")
  81.    if ($char -eq "N") {Exit(1)} else {Clear-Host}
  82. }
  83.  
  84. function Truncate-LogFiles {
  85.  
  86.    Write-Output "Fetching log files in ""$($PWD)"", please wait..."
  87.    Write-Output ""
  88.    $logFiles = Get-ChildItem -Path $PWD -File -Filter "*.log" -Recurse -Force -ErrorAction SilentlyContinue
  89.    if (-not $logFiles) {
  90.        Write-Warning "No log files found in directory: $($PWD)"
  91.        Return
  92.    }
  93.    Clear-Host
  94.  
  95.    foreach ($logFile in $logFiles) {
  96.  
  97.         if ($logFile.Length -eq 0) {
  98.            Continue
  99.        }
  100.  
  101.        $formattedFileSize = [FileUtils]::FormatFileSize($logFile.Length)
  102.        Write-Output "Truncating file: $($LogFile.FullName) ($($formattedFileSize)) ..."
  103.  
  104.        try {
  105.            # [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($logFile.FullName, [Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs, [Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin)
  106.            $fs = [System.IO.File]::OpenWrite($logFile.FullName)
  107.            $fs.SetLength(0)
  108.            $fs.Close()
  109.        }
  110.        catch {
  111.            Write-Host "Access denied to file, it may be in use." -ForegroundColor Yellow
  112.        }
  113.        Start-Sleep -MilliSeconds 50
  114.    }
  115.  
  116. }
  117.  
  118. function Show-GoodbyeScreen {
  119.    Write-Output ""
  120.    Write-Host "Operation Completed." -BackgroundColor Black -ForegroundColor Green
  121.    Write-Output ""
  122.    Write-Output "Press any key to exit..."
  123.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  124.    Exit(0)
  125. }
  126.  
  127. <#
  128. ===========================================================================================
  129. |                                                                                         |
  130. |                                         Main                                            |
  131. |                                                                                         |
  132. ===========================================================================================
  133. #>
  134.  
  135. [System.Console]::Title = "Truncate Log Files - by Elektro"
  136. [CultureInfo]::CurrentUICulture = "en-US"
  137.  
  138. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  139.  
  140. Show-WelcomeScreen
  141. Confirm-Continue
  142. Truncate-LogFiles
  143. Show-GoodbyeScreen
114  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.







Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                    Functions                                            |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. function Show-WelcomeScreen {
  10.    Clear-Host
  11.    Write-Output ""
  12.    Write-Output " $($host.ui.RawUI.WindowTitle)"
  13.    Write-Output " +=================================================+"
  14.    Write-Output " |                                                 |"
  15.    Write-Output " | This script will clear all the entries from the |"
  16.    Write-Output " | Windows event logs on the current computer, and |"
  17.    Write-Output " | display a table with the deletion results.      |"
  18.    Write-Output " |                                                 |"
  19.    Write-Output " +=================================================+"
  20.    Write-Output ""
  21. }
  22.  
  23. function Confirm-Continue {
  24.    Write-Host " Press 'Y' key to continue or 'N' key to exit."
  25.    Write-Host ""
  26.    Write-Host " -Continue? (Y/N)"
  27.    do {
  28.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  29.        $char = $key.Character.ToString().ToUpper()
  30.        if ($char -ne "Y" -and $char -ne "N") {
  31.            [console]::beep(1500, 500)
  32.        }
  33.    } while ($char -ne "Y" -and $char -ne "N")
  34.    if ($char -eq "N") {Exit(1)} else {Clear-Host}
  35. }
  36.  
  37. # 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
  38. function Clear-EventLogs ($computerName=".") {
  39.    try {
  40.        $logsBefore = Get-EventLog -ComputerName $computerName -List | Select-Object Log, @{Name="Before";Expression={$_.Entries.Count}}
  41.        Get-EventLog -ComputerName $computername -List | ForEach-Object {$_.Log} | ForEach-Object {
  42.            Write-Host "Deleting $_ event logs..."
  43.            Clear-EventLog -ComputerName $computername -LogName $_
  44.        }
  45.        $logsAfter = Get-EventLog -ComputerName $computerName -List | Select-Object Log, @{Name="After";Expression={$_.Entries.Count}}
  46.        $logsDiff = $logsBefore | ForEach-Object {
  47.            $log = $_.Log
  48.            $Before = $_.Before
  49.            $After = ($logsAfter | Where-Object {$_.Log -eq $log}).After
  50.            [PSCustomObject]@{
  51.                Log = $log
  52.                Before = $Before
  53.                After = $After
  54.            }
  55.        }
  56.        $logsDiff|Format-Table
  57.    } catch {
  58.        Write-Host "Something went wrong when calling '$($MyInvocation.MyCommand.Name)' method:"
  59.        Write-Host ""
  60.        Write-Warning ($_.Exception.InnerException.Message)
  61.        Write-Host ""
  62.        Write-Error -Message ($_.Exception | Format-List * -Force | Out-String)
  63.        Write-Host ""
  64.        Write-Host "Press any key to exit..."
  65.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  66.        Exit(1)
  67.    }
  68. }
  69.  
  70. function Show-GoodbyeScreen {
  71.    Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  72.    Write-Host ""
  73.    Write-Host "Press any key to exit..."
  74.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  75. }
  76.  
  77. <#
  78. ===========================================================================================
  79. |                                                                                         |
  80. |                                         Main                                            |
  81. |                                                                                         |
  82. ===========================================================================================
  83. #>
  84.  
  85. [System.Console]::Title = "Windows Event Logs Cleaner - by Elektro"
  86. [CultureInfo]::CurrentUICulture = "en-US"
  87.  
  88. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  89.  
  90. Show-WelcomeScreen
  91. Confirm-Continue
  92. Clear-EventLogs -ComputerName "."
  93. Show-GoodbyeScreen
  94. Exit(0)
115  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.











Código
  1. Import-Module Microsoft.PowerShell.Management
  2.  
  3. [System.Console]::Title = "3rd Party Driver Backup Tool - by Elektro"
  4. [CultureInfo]::CurrentUICulture = "en-US"
  5.  
  6. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  7.  
  8. $Timestamp = Get-Date -Format "yyyy&#8725;MMMM&#8725;dd HH&#42889;mm&#42889;ss"
  9.  
  10. $OutputDirectory = "$env:USERPROFILE\Desktop\3rd Party Drivers Backup $Timestamp"
  11.  
  12. Do {
  13.    Clear-Host
  14.    Write-Host ""
  15.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  16.    Write-Host " +===========================================================+"
  17.    Write-Host " |                                                           |"
  18.    Write-Host " | This script will make a full backup of the 3rd party      |"
  19.    Write-Host " | device drivers that are installed in the current machine, |"
  20.    Write-Host " | and will save them into the user's desktop directory.     |"
  21.    Write-Host " |                                                           |"
  22.    Write-Host " +===========================================================+"
  23.    Write-Host ""
  24.    Write-Host " CURRENT SCRIPT CONFIG:"
  25.    Write-Host " ----------------------"
  26.    Write-Host ""
  27.    Write-Host " Output Directory:"
  28.    Write-Host " $OutputDirectory"
  29.    Write-Host " ___________________________________________________________"
  30.    Write-Host ""
  31.    Write-Host " -Continue? (Y/N)"
  32.    $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  33.    $char = $key.Character.ToString().ToUpper()
  34.    if ($char -ne "Y" -and $char -ne "N") {
  35.        [console]::beep(1500, 500)
  36.    }    
  37. } while ($char -ne "Y" -and $char -ne "N")
  38. if ($char -eq "N") {Exit(1)} else {Clear-Host}
  39.  
  40. if (-not (Test-Path $OutputDirectory)) {
  41.    New-Item -Path "$OutputDirectory" -ItemType "Directory" -Force | Out-Null
  42. } & {
  43.    $psi = New-Object System.Diagnostics.ProcessStartInfo
  44.    $psi.FileName = "DISM.exe"
  45.    $psi.Arguments = "/Online /Export-Driver /Destination:""$OutputDirectory"""
  46.    $psi.UseShellExecute = $false
  47.  
  48.    $p = [System.Diagnostics.Process]::Start($psi)
  49.    $p.WaitForExit()
  50.    $dismExitCode = $p.ExitCode
  51.  
  52.    if ($dismExitCode -eq 0) {
  53.        Write-Host ""
  54.        Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  55.        Write-Host ""
  56.    } else {
  57.        Write-Host ""
  58.        Write-Host "Operation Failed. Confirm to delete the output directory:" -BackgroundColor Black -ForegroundColor Red
  59.        Write-Host ""
  60.        Remove-Item -Path "$OutputDirectory" -Recurse -Force -ErrorAction SilentlyContinue -Confirm:$true
  61.    }
  62. }
  63.  
  64. Write-Host ""
  65. Write-Host "Press any key to exit..."
  66. $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  67. Exit($dismExitCode)
116  Foros Generales / Foro Libre / Re: ¿En qué link puedo leer gratis lo que leyó William Kamkwamba (el africano que...)? en: 3 Marzo 2024, 20:34 pm
Hola.

-> internet_archive_downloader para Chrome y Firefox. Va como la seda. Las descargas se completan en pocos minutos.

De nada.
117  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.









Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $rarExecutablePath = "C:\Program Files\WinRAR\rar.exe"
  10. $dictionarySizes   = @(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048)
  11. $toleranceSizeDiff = "1MB"
  12. $keepOnlySmallestRarFile  = $true
  13. $sendRarFilesToRecycleBin = $false
  14.  
  15. $compressedFileTypesArchive = @(
  16.    "7z" , "arc", "bz2" , "bzip", "bzip2",
  17.    "gz" , "gz2", "gza" , "gzi" , "gzip" ,
  18.    "lha", "lz" , "lz4" , "lzh" , "lzma" ,
  19.    "rar", "sfx", "tgz" , "tlz" , "tlzma",
  20.    "uha", "zip", "zipx", "zpaq"
  21. )
  22.  
  23. $compressedFileTypesAudio = @(
  24.    "aac", "ac3", "fla","flac",
  25.    "m4a", "mp3", "ogg", "ogm",
  26.    "usm", "wma"
  27. )
  28.  
  29. $compressedFileTypesVideo = @(
  30.    "asf", "avc", "avi" , "bik" , "bk2" , "f4v" , "flv" ,
  31.    "m1v", "m2t", "m2ts", "m2v" , "m4v" , "mpv4",
  32.    "mkv", "mov", "mp4" , "mpeg", "mpg" , "mts" ,
  33.    "qt" , "ts" , "vob" , "vp6" , "webm", "wmv"
  34. )
  35.  
  36. $compressedFileTypesOther = @(
  37.    "avif", "jpeg", "jpg" , "gif" , "pdf",
  38.    "pam" , "paq6", "paq7", "paq8",
  39.    "par" , "par2", "wad"
  40. )
  41.  
  42.  
  43. [string]$fileTypesToKeepUncompressed = (
  44.    $compressedFileTypesArchive +
  45.    $compressedFileTypesAudio +
  46.    $compressedFileTypesVideo +
  47.    $compressedFileTypesOther
  48. ) -join ';'
  49.  
  50. <#
  51. ===========================================================================================
  52. |                                                                                         |
  53. |                    rar.exe commands (only those used in this script)                    |
  54. |                                                                                         |
  55. ===========================================================================================
  56.  
  57. <Commands>
  58.  a             Add files to archive
  59.  
  60. <Switches>
  61.  -am[s,r]       Archive name and time [save, restore]
  62.  -c-            Disable comments show
  63.  -cfg-          Ignore configuration file and RAR environment variable.
  64.  -dh            Open shared files
  65.  -ep1           Exclude base directory from names
  66.  -ht[b|c]       Select hash type [BLAKE2,CRC32] for file checksum
  67.  -id[c,d,n,p,q] Display or disable messages
  68.  -ilog[name]    Log errors to file
  69.  -isnd[-]       Control notification sounds
  70.  -m<0..5>       Set compression level (0-store...3-default...5-maximal)
  71.  -ma[4|5]       Specify a version of archiving format
  72.  -md<n>[k,m,g]  Dictionary size in KB, MB or GB
  73.  -ms[list]      Specify file types to store.
  74.  -o[+|-]        Set the overwrite mode
  75.  -oc            Set NTFS Compressed attribute.
  76.  -oh            Save hard links as the link instead of the file
  77.  -oi[0-4][:min] Save identical files as references
  78.  -ol[a]         Process symbolic links as the link [absolute paths]
  79.  -oni           Allow potentially incompatible names
  80.  -qo[-|+]       Add quick open information [none|force]
  81.  -r             Recurse subdirectories
  82.  -ri<P>[:<S>]   Set priority (0-default,1-min..15-max) and sleep time in ms
  83.  -s-            Disable solid archiving
  84.  -t             Test files after archiving
  85.  -tk            Keep original archive time
  86.  -tl            Set archive time to newest file
  87.  -ts[m,c,a,p]   Save or restore time (modification, creation, access, preserve)
  88.  -u             Update files
  89.  -w<path>       Assign work directory
  90. #>
  91.  
  92. <#
  93. ===========================================================================================
  94. |                                                                                         |
  95. |                                        .NET Code                                        |
  96. |                                                                                         |
  97. ===========================================================================================
  98. #>
  99.  
  100. Add-Type -TypeDefinition @"
  101. using System;
  102. using System.Runtime.InteropServices;
  103.  
  104. public class Win32Functions {
  105.    [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
  106.    public static extern long StrFormatByteSizeW(long fileSize, System.Text.StringBuilder buffer, int bufferSize);
  107. }
  108. "@
  109.  
  110. <#
  111. ===========================================================================================
  112. |                                                                                         |
  113. |                                    Functions                                            |
  114. |                                                                                         |
  115. ===========================================================================================
  116. #>
  117. function Show-WelcomeScreen {
  118.    Clear-Host
  119.    Write-Host ""
  120.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  121.    Write-Host " +========================================================+"
  122.    Write-Host " |                                                        |"
  123.    Write-Host " | This script will use RAR.exe to compress each file in  |"
  124.    Write-Host " | the current working directory individually, each using |"
  125.    Write-Host " | different dictionary sizes, with max. compression,     |"
  126.    Write-Host " | generating this way multiple RAR files for evaluating  |"
  127.    Write-Host " | compression rates on these dictionary sizes.           |"
  128.    Write-Host " |                                                        |"
  129.    Write-Host " +=========================================================+"
  130.    Write-Host ""
  131.    Write-Host " Script Settings            " -ForegroundColor DarkGray
  132.    Write-Host " ===========================" -ForegroundColor DarkGray
  133.    Write-Host " RAR Executable Path: $([System.IO.Path]::GetFullPath($rarExecutablePath))" -ForegroundColor Gray
  134.    Write-Host "" -ForegroundColor DarkGray
  135.    Write-Host " Dictionary Sizes (Megabyte): $($dictionarySizes -join ', ')" -ForegroundColor Gray
  136.    Write-Host " The script will create a RAR archive for each specified dictionary size." -ForegroundColor DarkGray
  137.    Write-Host "" -ForegroundColor DarkGray
  138.    Write-Host " File Types To Keep Uncompressed: `$keepCompressedFileTypesUncompressed" -ForegroundColor Gray
  139.    Write-Host " The script will instruct RAR to don't compress the specified known compressed file types." -ForegroundColor DarkGray
  140.    Write-Host " (See `$keepCompressedFileTypesUncompressed variable definition to manage the file types)" -ForegroundColor DarkGray
  141.    Write-Host "" -ForegroundColor DarkGray
  142.    Write-Host " Tolerance File Size Difference: $toleranceSizeDiff" -ForegroundColor Gray
  143.    Write-Host " Any newly created RAR file whose file size compared to previously   " -ForegroundColor DarkGray
  144.    Write-Host " created RAR files is within the specified tolerance value, it will be deleted." -ForegroundColor DarkGray
  145.    Write-Host " For example, if `$toleranceSizeDiff value is 1MB:" -ForegroundColor DarkGray
  146.    Write-Host " If a created RAR file of 32 MB dict. size has a file size of 100 MB," -ForegroundColor DarkGray
  147.    Write-Host " and then a newly created RAR file of 64 MB dict. size has a file size of 99 MB, " -ForegroundColor DarkGray
  148.    Write-Host " the RAR file of 64 MB dict. size will be deleted because it only differs in 1MB or less." -ForegroundColor DarkGray
  149.    Write-Host "" -ForegroundColor DarkGray
  150.    Write-Host " Keep only smallest rar file: $keepOnlySmallestRarFile" -ForegroundColor Gray
  151.    Write-Host " If True, the script will delete any newly created RAR file " -ForegroundColor DarkGray
  152.    Write-Host " whose file size is bigger than previously created RAR files." -ForegroundColor DarkGray
  153.    Write-Host " Note: it takes into account the specified `$toleranceSizeDiff value." -ForegroundColor DarkGray
  154.    Write-Host "" -ForegroundColor DarkGray
  155.    Write-Host " Send RAR files to recycle bin: $sendRarFilesToRecycleBin" -ForegroundColor Gray
  156.    Write-Host " If True, the script will send RAR files to recycle bin instead of permanently deleting them." -ForegroundColor DarkGray
  157.    Write-Host ""
  158. }
  159.  
  160. function Confirm-Continue {
  161.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  162.    Write-Host ""
  163.    Write-Host " -Continue? (Y/N)"
  164.    do {
  165.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  166.        $char = $key.Character.ToString().ToUpper()
  167.        if ($char -ne "Y" -and $char -ne "N") {
  168.            [console]::beep(1500, 500)
  169.        }
  170.    } while ($char -ne "Y" -and $char -ne "N")
  171.    if ($char -eq "N") {Exit(1)} else {Clear-Host}
  172. }
  173.  
  174. function Compress-Files {
  175.    Add-Type -AssemblyName Microsoft.VisualBasic
  176.  
  177.    $dictionarySizes = $dictionarySizes | Sort-Object
  178.  
  179.    # Partir y formatear la cadena de file types para acomodarlo a la linea de argumentos de rar.exe
  180.    if (-not [String]::IsNullOrEmpty($fileTypesToKeepUncompressed)) {
  181.        $fileTypeTokens = $fileTypesToKeepUncompressed -split ';'
  182.        $fileTypesArgumentLines = @()
  183.        for ($i = 0; $i -lt $fileTypeTokens.Count; $i += 20) {
  184.            $fileTypesArgumentLines += "-ms" + ($fileTypeTokens[$i..($i + 19)] -join ';') + [Environment]::NewLine
  185.        }
  186.        if ($fileTypesArgumentLines.Count -gt 0) {
  187.            $fileTypesArgumentLines[-1] = $fileTypesArgumentLines[-1] -replace [Environment]::NewLine, ''
  188.        }
  189.    } else {
  190.        $fileTypesArgumentLines = "-ms "
  191.    }
  192.  
  193.    foreach ($inputFile in Get-ChildItem -LiteralPath "$PSScriptRoot" -File) {
  194.  
  195.        if ($inputFile.Name -eq [System.IO.Path]::GetFileName($PSCommandPath)) {
  196.            continue
  197.        }
  198.  
  199.        # Keeps track of created rar files by rar.exe
  200.        $createdRarFiles = New-Object System.Collections.Generic.List[System.IO.FileInfo]
  201.  
  202.        foreach ($size in $dictionarySizes) {
  203.  
  204.            if (($size -ne $dictionarySizes[0]) -and ($inputFile.Length * 4) -le ($size * 1MB)) {
  205.                $formattedSize = Format-FileSize -fileSize $inputFile.Length
  206.                Write-Host "Ignoring compression with too big dictionary size of $size mb for a $formattedSize file: `"$($inputFile.Name)`"..." -ForegroundColor Yellow
  207.                continue
  208.            }
  209.  
  210.            $outputRarFilePath   = "$($inputFile.FullName)_$($size)mb.rar"
  211.            $errorLogFilePath = "$($inputFile.FullName)_$($size)mb_error.log"
  212.  
  213.            $arguments = @(
  214.                " a -u -ams -c- -cfg- -dh -ep1 -htb -idcdn -isnd- -iver -m5 -ma5 -md$($size)m",
  215.                " -o+ -oc -oh -oi2 -ol -oni -qo+ -r -ri0:0 -s- -t -tk -tl -tsmca+",
  216.                " $fileTypesArgumentLines",
  217.                " -x`"*\$($MyInvocation.MyCommand.Name)`"",
  218.                " -w`"$($env:TEMP)`"",
  219.                " -ilog`"$errorLogFilePath`"",
  220.                " -- `"$outputRarFilePath`"",
  221.                " -- `"$($inputFile.FullName)`""
  222.            )
  223.  
  224.            Write-Host "Compressing file with $size mb dictionary dize: `"$($inputFile.Name)`"..."
  225.            #Write-Host ""
  226.            #Write-Host "rar.exe arguments:" -ForegroundColor DarkGray
  227.            #Write-Host ($arguments -join [Environment]::NewLine) -ForegroundColor DarkGray
  228.  
  229.            $psi = New-Object System.Diagnostics.ProcessStartInfo
  230.            $psi.FileName = $rarExecutablePath
  231.            $psi.Arguments = $arguments -join ' '
  232.            $psi.RedirectStandardOutput = $false
  233.            $psi.UseShellExecute = $false
  234.            $psi.CreateNoWindow = $false
  235.  
  236.            $process = [System.Diagnostics.Process]::Start($psi)
  237.            $process.WaitForExit()
  238.  
  239.            $outputRarFile = New-Object System.IO.FileInfo($outputRarFilePath)
  240.            $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length
  241.            Write-Host ""
  242.            Write-Host "Created rar with file name: $($outputRarFile.Name) ($formattedOutputRarFileSize)" -ForegroundColor DarkGreen
  243.  
  244.            if ($toleranceSizeDiff -ne $null) {
  245.                if ($createdRarFiles.Count -ne 0) {
  246.                    $outputRarFileMB = [Math]::Floor($outputRarFile.Length / $toleranceSizeDiff)
  247.                    $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length
  248.  
  249.                    foreach ($rarFile in $createdRarFiles) {
  250.                        if ($rarFile.Exists) {
  251.                            $sizeMB = [Math]::Floor($rarFile.Length / $toleranceSizeDiff)
  252.                            $formattedRarFileSize = Format-FileSize -fileSize $rarFile.Length
  253.                            if ($outputRarFileMB -eq $sizeMB) {
  254.                                Write-Host ""
  255.                                Write-Host "File size of this created RAR file ($formattedOutputRarFileSize) is within the $toleranceSizeDiff tolerance difference" -ForegroundColor DarkGray
  256.                                Write-Host "than a previously created RAR file ($formattedRarFileSize) with smaller dictionary size..." -ForegroundColor DarkGray
  257.                                Write-Host "Deleting file: `"$($outputRarFile.Name)`" ($formattedOutputRarFileSize)..." -ForegroundColor Yellow
  258.                                if ($sendRarFilesToRecycleBin) {
  259.                                    [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  260.                                } else {
  261.                                    [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'DeletePermanently')
  262.                                }
  263.                                Write-Host "Deletion completed." -ForegroundColor Yellow
  264.                            }
  265.                        }
  266.                    }
  267.                }
  268.            }
  269.  
  270.            if (Test-Path -LiteralPath $outputRarFile.FullName -PathType Leaf) {
  271.                $createdRarFiles.Add($outputRarFile)
  272.            }
  273.            Write-Host ""
  274.        }
  275.  
  276.        if ($keepOnlySmallestRarFile -and $createdRarFiles.Count -gt 0) {
  277.            $existingFiles = $createdRarFiles | Where-Object { $_.Exists }
  278.            if ($existingFiles.Count -gt 0) {
  279.                Write-Host "`$keepOnlySmallestRarFile variable is `$True. Comparing file sizes of created RAR files..." -ForegroundColor Yellow
  280.                Write-Host ""
  281.                $smallestFile = $existingFiles | Sort-Object Length | Select-Object -First 1
  282.                foreach ($file in $existingFiles) {
  283.                    if ($file -ne $smallestFile) {
  284.                        $formattedFileSize = Format-FileSize -fileSize $file.Length
  285.                        Write-Host "Deleting file: `"$($file.Name)`" ($formattedFileSize)..." -ForegroundColor Yellow
  286.                        if ($sendRarFilesToRecycleBin) {
  287.                            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  288.                        } else {
  289.                            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'DeletePermanently')
  290.                        }
  291.                        Write-Host "Deletion completed." -ForegroundColor Yellow
  292.                        Write-Host ""
  293.                    }
  294.                }
  295.                $formattedSmallestFileSize = Format-FileSize -fileSize $smallestFile.Length
  296.                Write-Host "Smallest file kept: $($smallestFile.Name) ($formattedSmallestFileSize)" -ForegroundColor Green
  297.                Write-Host ""
  298.            }
  299.        }
  300.  
  301.    }
  302. }
  303.  
  304. function Format-FileSize {
  305.    param(
  306.        [long]$fileSize
  307.    )
  308.    $buffer = New-Object System.Text.StringBuilder 260
  309.    [Win32Functions]::StrFormatByteSizeW($fileSize, $buffer, $buffer.Capacity) | Out-Null
  310.    return $buffer.ToString()
  311. }
  312.  
  313. function Show-GoodbyeScreen {
  314.    Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  315.    Write-Host ""
  316.    Write-Host "Press any key to exit..."
  317.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  318.    Exit(0)
  319. }
  320.  
  321. <#
  322. ===========================================================================================
  323. |                                                                                         |
  324. |                                         Main                                            |
  325. |                                                                                         |
  326. ===========================================================================================
  327. #>
  328.  
  329. [System.Console]::Title = "RAR Multi-Compression Test Tool (Files) - by Elektro"
  330. #[System.Console]::SetWindowSize(150, 45)
  331. [CultureInfo]::CurrentUICulture = "en-US"
  332.  
  333. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  334.  
  335. Show-WelcomeScreen
  336. Confirm-Continue
  337. Compress-Files
  338. Show-GoodbyeScreen
  339.  
118  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.











Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $rarExecutablePath = "C:\Program Files\WinRAR\rar.exe"
  10. $dictionarySizes   = @(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048)
  11. $toleranceSizeDiff = "1MB"
  12. $keepOnlySmallestRarFile  = $true
  13. $sendRarFilesToRecycleBin = $false
  14.  
  15. $compressedFileTypesArchive = @(
  16.    "7z" , "arc", "bz2" , "bzip", "bzip2",
  17.    "gz" , "gz2", "gza" , "gzi" , "gzip" ,
  18.    "lha", "lz" , "lz4" , "lzh" , "lzma" ,
  19.    "rar", "sfx", "tgz" , "tlz" , "tlzma",
  20.    "uha", "zip", "zipx", "zpaq"
  21. )
  22.  
  23. $compressedFileTypesAudio = @(
  24.    "aac", "ac3", "fla","flac",
  25.    "m4a", "mp3", "ogg", "ogm",
  26.    "usm", "wma"
  27. )
  28.  
  29. $compressedFileTypesVideo = @(
  30.    "asf", "avc", "avi" , "bik" , "bk2" , "f4v" , "flv" ,
  31.    "m1v", "m2t", "m2ts", "m2v" , "m4v" , "mpv4",
  32.    "mkv", "mov", "mp4" , "mpeg", "mpg" , "mts" ,
  33.    "qt" , "ts" , "vob" , "vp6" , "webm", "wmv"
  34. )
  35.  
  36. $compressedFileTypesOther = @(
  37.    "avif", "jpeg", "jpg" , "gif" , "pdf",
  38.    "pam" , "paq6", "paq7", "paq8",
  39.    "par" , "par2", "wad"
  40. )
  41.  
  42.  
  43. [string]$fileTypesToKeepUncompressed = (
  44.    $compressedFileTypesArchive +
  45.    $compressedFileTypesAudio +
  46.    $compressedFileTypesVideo +
  47.    $compressedFileTypesOther
  48. ) -join ';'
  49.  
  50. <#
  51. ===========================================================================================
  52. |                                                                                         |
  53. |                    rar.exe commands (only those used in this script)                    |
  54. |                                                                                         |
  55. ===========================================================================================
  56.  
  57. <Commands>
  58.  a             Add files to archive
  59.  
  60. <Switches>
  61.  -am[s,r]       Archive name and time [save, restore]
  62.  -c-            Disable comments show
  63.  -cfg-          Ignore configuration file and RAR environment variable.
  64.  -dh            Open shared files
  65.  -ep1           Exclude base directory from names
  66.  -ht[b|c]       Select hash type [BLAKE2,CRC32] for file checksum
  67.  -id[c,d,n,p,q] Display or disable messages
  68.  -ilog[name]    Log errors to file
  69.  -isnd[-]       Control notification sounds
  70.  -m<0..5>       Set compression level (0-store...3-default...5-maximal)
  71.  -ma[4|5]       Specify a version of archiving format
  72.  -md<n>[k,m,g]  Dictionary size in KB, MB or GB
  73.  -ms[list]      Specify file types to store.
  74.  -o[+|-]        Set the overwrite mode
  75.  -oc            Set NTFS Compressed attribute.
  76.  -oh            Save hard links as the link instead of the file
  77.  -oi[0-4][:min] Save identical files as references
  78.  -ol[a]         Process symbolic links as the link [absolute paths]
  79.  -oni           Allow potentially incompatible names
  80.  -qo[-|+]       Add quick open information [none|force]
  81.  -r             Recurse subdirectories
  82.  -ri<P>[:<S>]   Set priority (0-default,1-min..15-max) and sleep time in ms
  83.  -s-            Disable solid archiving
  84.  -t             Test files after archiving
  85.  -tk            Keep original archive time
  86.  -tl            Set archive time to newest file
  87.  -ts[m,c,a,p]   Save or restore time (modification, creation, access, preserve)
  88.  -u             Update files
  89.  -w<path>       Assign work directory
  90. #>
  91.  
  92. <#
  93. ===========================================================================================
  94. |                                                                                         |
  95. |                                        .NET Code                                        |
  96. |                                                                                         |
  97. ===========================================================================================
  98. #>
  99.  
  100. Add-Type -TypeDefinition @"
  101. using System;
  102. using System.Runtime.InteropServices;
  103.  
  104. public class Win32Functions {
  105.    [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
  106.    public static extern long StrFormatByteSizeW(long fileSize, System.Text.StringBuilder buffer, int bufferSize);
  107. }
  108. "@
  109.  
  110. <#
  111. ===========================================================================================
  112. |                                                                                         |
  113. |                                    Functions                                            |
  114. |                                                                                         |
  115. ===========================================================================================
  116. #>
  117. function Show-WelcomeScreen {
  118.    Clear-Host
  119.    Write-Host ""
  120.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  121.    Write-Host " +==========================================================+"
  122.    Write-Host " |                                                          |"
  123.    Write-Host " | This script will use RAR.exe to compress each directory  |"
  124.    Write-Host " | in the current working directory individually, each      |"
  125.    Write-Host " | using different dictionary sizes, with max. compression, |"
  126.    Write-Host " | generating this way multiple RAR files for evaluating    |"
  127.    Write-Host " | compression rates on these dictionary sizes.             |"
  128.    Write-Host " |                                                          |"
  129.    Write-Host " +==========================================================+"
  130.    Write-Host ""
  131.    Write-Host " Script Settings            " -ForegroundColor DarkGray
  132.    Write-Host " ===========================" -ForegroundColor DarkGray
  133.    Write-Host " RAR Executable Path: $([System.IO.Path]::GetFullPath($rarExecutablePath))" -ForegroundColor Gray
  134.    Write-Host "" -ForegroundColor DarkGray
  135.    Write-Host " Dictionary Sizes (Megabyte): $($dictionarySizes -join ', ')" -ForegroundColor Gray
  136.    Write-Host " The script will create a RAR archive for each specified dictionary size." -ForegroundColor DarkGray
  137.    Write-Host "" -ForegroundColor DarkGray
  138.    Write-Host " File Types To Keep Uncompressed: `$keepCompressedFileTypesUncompressed" -ForegroundColor Gray
  139.    Write-Host " The script will instruct RAR to don't compress the specified known compressed file types." -ForegroundColor DarkGray
  140.    Write-Host " (See `$keepCompressedFileTypesUncompressed variable definition to manage the file types)" -ForegroundColor DarkGray
  141.    Write-Host "" -ForegroundColor DarkGray
  142.    Write-Host " Tolerance File Size Difference: $toleranceSizeDiff" -ForegroundColor Gray
  143.    Write-Host " Any newly created RAR file whose file size compared to previously   " -ForegroundColor DarkGray
  144.    Write-Host " created RAR files is within the specified tolerance value, it will be deleted." -ForegroundColor DarkGray
  145.    Write-Host " For example, if `$toleranceSizeDiff value is 1MB:" -ForegroundColor DarkGray
  146.    Write-Host " If a created RAR file of 32 MB dict. size has a file size of 100 MB," -ForegroundColor DarkGray
  147.    Write-Host " and then a newly created RAR file of 64 MB dict. size has a file size of 99 MB, " -ForegroundColor DarkGray
  148.    Write-Host " the RAR file of 64 MB dict. size will be deleted because it only differs in 1MB or less." -ForegroundColor DarkGray
  149.    Write-Host "" -ForegroundColor DarkGray
  150.    Write-Host " Keep only smallest rar file: $keepOnlySmallestRarFile" -ForegroundColor Gray
  151.    Write-Host " If True, the script will delete any newly created RAR file " -ForegroundColor DarkGray
  152.    Write-Host " whose file size is bigger than previously created RAR files." -ForegroundColor DarkGray
  153.    Write-Host " Note: it takes into account the specified `$toleranceSizeDiff value." -ForegroundColor DarkGray
  154.    Write-Host "" -ForegroundColor DarkGray
  155.    Write-Host " Send RAR files to recycle bin: $sendRarFilesToRecycleBin" -ForegroundColor Gray
  156.    Write-Host " If True, the script will send RAR files to recycle bin instead of permanently deleting them." -ForegroundColor DarkGray
  157.    Write-Host ""
  158. }
  159.  
  160. function Confirm-Continue {
  161.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  162.    Write-Host ""
  163.    Write-Host " -Continue? (Y/N)"
  164.    do {
  165.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  166.        $char = $key.Character.ToString().ToUpper()
  167.        if ($char -ne "Y" -and $char -ne "N") {
  168.            [console]::beep(1500, 500)
  169.        }
  170.    } while ($char -ne "Y" -and $char -ne "N")
  171.    if ($char -eq "N") {Exit(1)} else {Clear-Host}
  172. }
  173.  
  174. function Compress-Files {
  175.    Add-Type -AssemblyName Microsoft.VisualBasic
  176.  
  177.    $dictionarySizes = $dictionarySizes | Sort-Object
  178.  
  179.    # Partir y formatear la cadena de file types para acomodarlo a la linea de argumentos de rar.exe
  180.    if (-not [String]::IsNullOrEmpty($fileTypesToKeepUncompressed)) {
  181.        $fileTypeTokens = $fileTypesToKeepUncompressed -split ';'
  182.        $fileTypesArgumentLines = @()
  183.        for ($i = 0; $i -lt $fileTypeTokens.Count; $i += 20) {
  184.            $fileTypesArgumentLines += "-ms" + ($fileTypeTokens[$i..($i + 19)] -join ';') + [Environment]::NewLine
  185.        }
  186.        if ($fileTypesArgumentLines.Count -gt 0) {
  187.            $fileTypesArgumentLines[-1] = $fileTypesArgumentLines[-1] -replace [Environment]::NewLine, ''
  188.        }
  189.    } else {
  190.        $fileTypesArgumentLines = "-ms "
  191.    }
  192.  
  193.    foreach ($dir in Get-ChildItem -LiteralPath "$PSScriptRoot" -Directory) {
  194.  
  195.        $dirSizeBytes = (Get-ChildItem -LiteralPath "$($dir.FullName)" -Recurse | Measure-Object -Property Length -sum).Sum
  196.  
  197.        # Keeps track of created rar files by rar.exe
  198.        $createdRarFiles = New-Object System.Collections.Generic.List[System.IO.FileInfo]
  199.  
  200.        foreach ($size in $dictionarySizes) {
  201.  
  202.            if (($size -ne $dictionarySizes[0]) -and ($dirSizeBytes * 4) -le ($size * 1MB)) {
  203.                $formattedDirSize = Format-FileSize -fileSize $dirSizeBytes
  204.                Write-Host "Ignoring compression with too big dictionary size of $size mb for a $formattedDirSize directory: `"$($dir.FullName)`"..." -ForegroundColor Yellow
  205.                continue
  206.            }
  207.  
  208.            $outputRarFilePath   = "$($dir.FullName)_$($size)mb.rar"
  209.            $errorLogFilePath = "$($dir.FullName)_$($size)mb_error.log"
  210.  
  211.            $arguments = @(
  212.                " a -u -ams -c- -cfg- -dh -ep1 -htb -idcdn -isnd- -iver -m5 -ma5 -md$($size)m",
  213.                " -o+ -oc -oh -oi2 -ol -oni -qo+ -r -ri0:0 -s- -t -tk -tl -tsmca+",
  214.                " $fileTypesArgumentLines",
  215.                " -x`"*\$($MyInvocation.MyCommand.Name)`"",
  216.                " -w`"$($env:TEMP)`"",
  217.                " -ilog`"$errorLogFilePath`"",
  218.                " -- `"$outputRarFilePath`"",
  219.                " -- `"$($dir.FullName)\*`""
  220.            )
  221.  
  222.            Write-Host "Compressing directory with $size mb dictionary dize: `"$($dir.Name)`"..."
  223.            #Write-Host ""
  224.            #Write-Host "rar.exe arguments:" -ForegroundColor DarkGray
  225.            #Write-Host ($arguments -join [Environment]::NewLine) -ForegroundColor DarkGray
  226.  
  227.            $psi = New-Object System.Diagnostics.ProcessStartInfo
  228.            $psi.FileName = $rarExecutablePath
  229.            $psi.Arguments = $arguments -join ' '
  230.            $psi.RedirectStandardOutput = $false
  231.            $psi.UseShellExecute = $false
  232.            $psi.CreateNoWindow = $false
  233.  
  234.            $process = [System.Diagnostics.Process]::Start($psi)
  235.            $process.WaitForExit()
  236.  
  237.            $outputRarFile = New-Object System.IO.FileInfo($outputRarFilePath)
  238.            $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length
  239.            Write-Host ""
  240.            Write-Host "Created rar with file name: $($outputRarFile.Name) ($formattedOutputRarFileSize)" -ForegroundColor DarkGreen
  241.  
  242.            if ($toleranceSizeDiff -ne $null) {
  243.                if ($createdRarFiles.Count -ne 0) {
  244.                    $outputRarFileMB = [Math]::Floor($outputRarFile.Length / $toleranceSizeDiff)
  245.                    $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length
  246.  
  247.                    foreach ($rarFile in $createdRarFiles) {
  248.                        if ($rarFile.Exists) {
  249.                            $sizeMB = [Math]::Floor($rarFile.Length / $toleranceSizeDiff)
  250.                            $formattedRarFileSize = Format-FileSize -fileSize $rarFile.Length
  251.                            if ($outputRarFileMB -eq $sizeMB) {
  252.                                Write-Host ""
  253.                                Write-Host "File size of this created RAR file ($formattedOutputRarFileSize) is within the $toleranceSizeDiff tolerance difference" -ForegroundColor DarkGray
  254.                                Write-Host "than a previously created RAR file ($formattedRarFileSize) with smaller dictionary size..." -ForegroundColor DarkGray
  255.                                Write-Host "Deleting file: `"$($outputRarFile.Name)`" ($formattedOutputRarFileSize)..." -ForegroundColor Yellow
  256.                                if ($sendRarFilesToRecycleBin) {
  257.                                    [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  258.                                } else {
  259.                                    [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'DeletePermanently')
  260.                                }
  261.                                Write-Host "Deletion completed." -ForegroundColor Yellow
  262.                            }
  263.                        }
  264.                    }
  265.                }
  266.            }
  267.  
  268.            if (Test-Path -LiteralPath $outputRarFile.FullName -PathType Leaf) {
  269.                $createdRarFiles.Add($outputRarFile)
  270.            }
  271.            Write-Host ""
  272.        }
  273.  
  274.        if ($keepOnlySmallestRarFile -and $createdRarFiles.Count -gt 0) {
  275.            $existingFiles = $createdRarFiles | Where-Object { $_.Exists }
  276.            if ($existingFiles.Count -gt 0) {
  277.                Write-Host "`$keepOnlySmallestRarFile variable is `$True. Comparing file sizes of created RAR files..." -ForegroundColor Yellow
  278.                Write-Host ""
  279.                $smallestFile = $existingFiles | Sort-Object Length | Select-Object -First 1
  280.                foreach ($file in $existingFiles) {
  281.                    if ($file -ne $smallestFile) {
  282.                        $formattedFileSize = Format-FileSize -fileSize $file.Length
  283.                        Write-Host "Deleting file: `"$($file.Name)`" ($formattedFileSize)..." -ForegroundColor Yellow
  284.                        if ($sendRarFilesToRecycleBin) {
  285.                            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  286.                        } else {
  287.                            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'DeletePermanently')
  288.                        }
  289.                        Write-Host "Deletion completed." -ForegroundColor Yellow
  290.                        Write-Host ""
  291.                    }
  292.                }
  293.                $formattedSmallestFileSize = Format-FileSize -fileSize $smallestFile.Length
  294.                Write-Host "Smallest file kept: $($smallestFile.Name) ($formattedSmallestFileSize)" -ForegroundColor Green
  295.                Write-Host ""
  296.            }
  297.        }
  298.  
  299.    }
  300. }
  301.  
  302. function Format-FileSize {
  303.    param(
  304.        [long]$fileSize
  305.    )
  306.    $buffer = New-Object System.Text.StringBuilder 260
  307.    [Win32Functions]::StrFormatByteSizeW($fileSize, $buffer, $buffer.Capacity) | Out-Null
  308.    return $buffer.ToString()
  309. }
  310.  
  311. function Show-GoodbyeScreen {
  312.    Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  313.    Write-Host ""
  314.    Write-Host "Press any key to exit..."
  315.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  316.    Exit(0)
  317. }
  318.  
  319. <#
  320. ===========================================================================================
  321. |                                                                                         |
  322. |                                         Main                                            |
  323. |                                                                                         |
  324. ===========================================================================================
  325. #>
  326.  
  327. [System.Console]::Title = "RAR Multi-Compression Test Tool (Directories) - by Elektro"
  328. #[System.Console]::SetWindowSize(150, 45)
  329. [CultureInfo]::CurrentUICulture = "en-US"
  330.  
  331. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  332.  
  333. Show-WelcomeScreen
  334. Confirm-Continue
  335. Compress-Files
  336. Show-GoodbyeScreen
  337.  
119  Programación / .NET (C#, VB.NET, ASP) / Re: crear / compilar en windows - ejecutar en linux en: 2 Marzo 2024, 11:57 am
¿A estas alturas de la vida?

A estas alturas de la vida, Xamarin sigue sin ofrecer soporte para programar directamente en el lenguaje VB.NET, por ejemplo. :-[

Y creo que con la tecnología multiplataforma .NET MAUI sucede lo mismo.

Hay cosas que simplemente no tienen la suficiente demanda o no les da la gana realizar el trabajo necesario para ofrecer soporte...



Respondiendo a tu duda principal y hasta donde yo se, ya lo respondí en mi aterior comentario pero lo diré de otra forma: no es posible desarrollar una aplicación de escritorio basada en Windows Forms de .NET Core y que sea compatible con Linux. Al menos no de forma nativa sin recurrir a Wine o cosas similares.

Aténtamente,
Elektro.
120  Foros Generales / Sugerencias y dudas sobre el Foro / PowerShell: Web Application Firewall (WAF) Blocked | Una regla de seguridad ha sido aplicada... en: 2 Marzo 2024, 11:07 am
Hola.

Abro este hilo por que he descubierto que al intentar publicar un post con el siguiente código escrito en el lenguaje Powershell:



Código:
$rarExecutablePath = "$ {env:ProgramFiles}\WinRAR\rar.exe"
(Nótese el espacio en blanco que he tenido que poner en la cadena "$ {env" para poder publicar este post.)

Me redirige a una página con el siguiente mensaje:

Citar
Web Application Firewall (WAF) Blocked

Una regla de seguridad ha sido aplicada. Si crees que es un error (falso positivo) contacta con webmaster@elhacker.net - Gracias.
The action you just performed triggered the security solution. If you think is false positive please contact to webmaster@elhacker.net - Thank you

No se si tendrá solución, simplemente lo comunico por si pudieran hacer algo con ello.

PD: Si no mando un e-mail a webmaster@elhacker.net es por que tal vez mi cuenta de correo esté bloqueada.

Aténtamente,
Elektro.
Páginas: 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 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines