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

 

 


Tema destacado: Sigue las noticias más importantes de seguridad informática en el Twitter! de elhacker.NET


  Mostrar Temas
Páginas: 1 [2] 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ... 105
11  Programación / Scripting / [APORTE] [PowerShell] Remove Windows Installer product registration for missing MSI packages en: 4 Marzo 2024, 15:10 pm
El siguiente script desarrollado en Powershell sirve para realizar un tipo de limpieza que CCleaner y limpiadores especializados del registro (como por ejemplo Wise Registry Cleaner) no pueden llevar a cabo:

Limpiar todo rastro, en el registro de Windows, de entradas a instaladores MSI que no se encuentren presentes en el sistema o que simplemente den conflictos pos fallas de instalación o desinstalación.

Es magia pura para solucionar cierto tipo de problemas relacionados con entradas de registro de paquetes MSI huérfanos.

Autor del código original: https://gist.github.com/heaths/77fbe0b44496960fab25c2eb0b9e8475



Código
  1. #Requires -Version 3
  2.  
  3. # https://gist.github.com/heaths/77fbe0b44496960fab25c2eb0b9e8475
  4.  
  5. [CmdletBinding(SupportsShouldProcess = $true)]
  6. param (
  7.    [Parameter(Position = 0, ValueFromPipeline = $true)]
  8.    [ValidateNotNullOrEmpty()]
  9.    [string[]] $ProductCode
  10. )
  11.  
  12. [System.Console]::Title = "Remove Windows Installer product registration for missing MSI packages"
  13. [CultureInfo]::CurrentUICulture = "en-US"
  14.  
  15. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  16.  
  17. $ErrorActionPreference = 'Stop'
  18. [int[]] $translation = 7,6,5,4,3,2,1,0,11,10,9,8,15,14,13,12,17,16,19,18,21,20,23,22,25,24,27,26,29,28,31,30
  19.  
  20. $loc = data {
  21.    ConvertFrom-StringData @'
  22.        Error_Elevation_Required = You must run this script in an elevated command prompt
  23.        Error_64Bit_Required = You must run this in a 64-bit command prompt
  24.        Error_PackageManagement_Required = Please install PackageManagement from http://go.microsoft.com/fwlink/?LinkID=746217
  25.        Process_Remove_Args1 = Remove registration for {0}
  26.        Verbose_Install_MSI = Installing the "MSI" module
  27.        Verbose_Scan_Missing = Scanning for products missing cached packages
  28.        Verbose_Remove_Key_Args1 = Removing key  : {0}
  29.        Verbose_Remove_Value_Args2 = Removing value: {0}\\{1}
  30.        Verbose_Remove_Source_Reg = Removing source registration
  31.        Verbose_Remove_Product_Reg = Removing product registration
  32.        Verbose_Remove_Upgrade_Reg = Removing upgrade registration
  33.        Verbose_Remove_Component_Reg = Removing component registration
  34.        Verbose_Found_Source_Args2 = Cache missing for {0} but found source at {1}
  35. '@
  36. }
  37.  
  38. $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
  39. $principal = New-Object System.Security.Principal.WindowsPrincipal $identity
  40. if (!$principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
  41.    throw $loc.Error_Elevation_Required
  42. }
  43.  
  44. if ([System.Environment]::Is64BitOperatingSystem) {
  45.    if (![System.Environment]::Is64BitProcess) {
  46.        throw $loc.Error_64Bit_Required
  47.    }
  48. }
  49.  
  50. $pack = {
  51.    param (
  52.        [string] $Guid
  53.    )
  54.  
  55.    if (!$Guid) {
  56.        return
  57.    }
  58.  
  59.    $Guid = (New-Object System.Guid $Guid).ToString("N").ToUpperInvariant()
  60.  
  61.    $sb = New-Object System.Text.StringBuilder $translation.Count
  62.    foreach ($i in $translation) {
  63.        $null = $sb.Append($Guid[$i])
  64.    }
  65.  
  66.    $sb.ToString()
  67. }
  68.  
  69. $test = {
  70.    param (
  71.        $Product
  72.    )
  73.  
  74.    if ($Product.PSPath -and ($Product | Test-Path)) {
  75.        return $true
  76.    }
  77.  
  78.    if ($Product.PackageName) {
  79.        $Product | Get-MSISource | ForEach-Object {
  80.            $path = Join-Path $_.Path $Product.PackageName
  81.            if ($path | Test-Path) {
  82.                Write-Host ($loc.Verbose_Found_Source_Args2 -f $Product.ProductCode, $path)
  83.                return $true
  84.            }
  85.        }
  86.    }
  87.  
  88.    $false
  89. }
  90.  
  91. $remove = {
  92.    param (
  93.        [string] $Key
  94.    )
  95.  
  96.    if (Test-Path $Key) {
  97.        Write-Host ($loc.Verbose_Remove_Key_Args1 -f $Key)
  98.        Remove-Item -Recurse -Force $Key
  99.    }
  100. }
  101.  
  102. $removeChild = {
  103.    param (
  104.        [string] $Key,
  105.        [string] $Name
  106.    )
  107.  
  108.    if (Test-Path $Key) {
  109.        Get-ChildItem $Key | ForEach-Object {
  110.            $obj = $_ | Get-ItemProperty
  111.            if ($obj.$Name -ne $null) {
  112.                Write-Host ($loc.Verbose_Remove_Value_Args2 -f $_.Name, $Name)
  113.                Remove-ItemProperty -Force -Name $Name -LiteralPath $_.PSPath
  114.  
  115.                $obj = Get-ItemProperty -LiteralPath $_.PSPath
  116.                if (!$obj) {
  117.                    Write-Host ($loc.Verbose_Remove_Key_Args1 -f $_.Name)
  118.                    Remove-Item -Recurse -Force -LiteralPath $_.PSPath
  119.                }
  120.            }
  121.        }
  122.    }
  123. }
  124.  
  125. if (!$ProductCode) {
  126.    # Install the MSI module if missing.
  127.    if (!(Get-Module -ListAvailable MSI)) {
  128.        Write-Host $loc.Verbose_Install_MSI
  129.  
  130.        # Make sure PackageManagement is installed (comes with WMF 5.0 / Windows 10).
  131.        if (!(Get-Module -ListAvailable PackageManagement)) {
  132.            throw $loc.Error_PackageManagement_Required
  133.        }
  134.  
  135.        Install-Module MSI -Scope CurrentUser -SkipPublisherCheck -Force
  136.    }
  137.  
  138.    Write-Host $loc.Verbose_Scan_Missing
  139.    foreach ($msi in (Get-MSIProductInfo -UserContext Machine)) {
  140.        if (!(&$test $msi)) {
  141.            $ProductCode += $msi.ProductCode
  142.        }
  143.    }
  144. }
  145.  
  146. foreach ($code in $ProductCode) {
  147.    if ($PSCmdlet.ShouldProcess($msi, $loc.Process_Remove_Args1 -f $code)) {
  148.        $packedProductCode = &$pack $code
  149.  
  150.        Write-Host $loc.Verbose_Remove_Source_Reg
  151.        &$remove "Registry::HKCL\SOFTWARE\Classes\Installer\Products\$packedProductCode"
  152.        &$remove "Registry::HKCL\SOFTWARE\Classes\Installer\Features\$packedProductCode"
  153.        &$remove "Registry::HKLM\SOFTWARE\Classes\Installer\Products\$packedProductCode"
  154.        &$remove "Registry::HKLM\SOFTWARE\Classes\Installer\Features\$packedProductCode"
  155.  
  156.        Write-Host $loc.Verbose_Remove_Product_Reg
  157.        &$remove "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\$packedProductCode"
  158.        &$remove "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$code"
  159.        &$remove "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\$packedProductCode"
  160.        &$remove "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$code"
  161.        &$remove "Registry::HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\$code"
  162.  
  163.        Write-Host $loc.Verbose_Remove_Upgrade_Reg
  164.        &$removeChild "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UpgradeCodes" $packedProductCode
  165.        &$removeChild "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UpgradeCodes" $packedProductCode
  166.  
  167.        Write-Host $loc.Verbose_Remove_Component_Reg
  168.        &$removeChild "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components" $packedProductCode
  169.        &$removeChild "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components" $packedProductCode
  170.  
  171.    }
  172. }
  173.  
  174. Write-Host "Press any key to exit..."
  175. $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  176. Exit(0)
  177.  
  178. <#
  179. .SYNOPSIS
  180. Removes Windows Installer product registrtation for missing or specified MSIs
  181. .DESCRIPTION
  182. If Windows Installer product registration is corrupt (exit code 1610) or package
  183. sources are missing (exit code 1603, error message 1714; or exit code 1612),
  184. you can use this script in an elevated PowerShell command shell to clean up the
  185. registration is a transactional manner to avoid making machine state worse.
  186. Please note that this should be a last resort and only for those issues above.
  187. The old msizap.exe program was frought with issues and can make matters worse
  188. if not used properly.
  189. .PARAMETER ProductCode
  190. Optional list of ProductCode to clean up; otherwise, ProductCodes are scanned
  191. from products with missing sources.
  192. .EXAMPLE
  193. PS> Unregister-MissingMSIs.ps1
  194. Removes per-machine product registration for products with missing cached MSIs.
  195. .EXAMPLE
  196. PS> Unregister-MissingMSIs.ps1 '{7B88D6BB-A664-4E5A-AB81-C435C8639A4D}'
  197. Remove per-machine product registration for the specified ProductCode only.
  198. #>
12  Programación / Scripting / [APORTE] [BATCH] FFMPEG | Convert Video to MP4 - Sony Vegas Compatible en: 4 Marzo 2024, 14:59 pm
El siguiente Batch-script, dependiente del programa de terceros FFMPEG, tiene la función de convertir un archivo de video (por lo general, MKV) a un formato MP4 que será compatible para la edición del video en los productos de Sony VEGAS.





Código
  1. @Echo OFF & CHCP 1252 >NUL & Title FFMPEG Convert Video to MP4 - Sony Vegas Compatible - Tool by Elektro
  2.  
  3. ECHO: This script will convert the source video file
  4. ECHO: to a MP4 video compatible with Sony Vegas.
  5.  
  6. IF "%~1" EQU "" (
  7.    ECHO: ERROR. INPUT FILE IS NOT DEFINED.
  8.    ECHO: YOU MUST DROP A MKV FILE TO THIS BATCH-FILE.
  9.    ECHO+
  10.    ECHO: This program will exit now...
  11.    ECHO+
  12.    Pause
  13.    Exit /B 1
  14. )
  15.  
  16. ECHO: Input  file: "%~1"
  17. ECHO: Output file: "%~dpn1_VEGAS.mp4"
  18.  
  19. CHOICE /C YN /M "Continue?"
  20. IF %ERRORLEVEL% EQU 2 (
  21.    Exit /B 1
  22. ) ELSE (
  23.    CLS
  24. )
  25.  
  26. IF NOT EXIST "%~dp0ffmpeg.exe" (
  27.    ECHO: ERROR. FILE DOES NOT EXIST: "%~dp0ffmpeg.exe"
  28.    ECHO: This program will exit now...
  29.    ECHO+
  30.    Pause
  31.    Exit /B 1
  32. )
  33.  
  34. :::::::::::::::::::::::::::::::::::::::::::::::::::::::
  35.  
  36. REM How to encode Vegas-compatible H.264 file using FFmpeg:
  37. REM http://www.konstantindmitriev.ru/blog/2014/03/02/how-to-encode-vegas-compatible-h-264-file-using-ffmpeg/
  38.  
  39. ECHO+Choose a encoding preset:
  40. ECHO+ [1] ultrafast
  41. ECHO+ [2] superfast
  42. ECHO+ [3] veryfast
  43. ECHO+ [4] faster
  44. ECHO+ [5] fast
  45. ECHO+ [6] medium – default preset
  46. ECHO+ [7] slow
  47. ECHO+ [8] slower
  48. ECHO+ [9] veryslow
  49. ECHO+ [0] Exit
  50. CHOICE /C "0123456789" /M ""
  51.  
  52. IF %ERRORLEVEL% EQU  1 (Exit)
  53. IF %ERRORLEVEL% EQU  2 (SET "preset=ultrafast")
  54. IF %ERRORLEVEL% EQU  3 (SET "preset=superfast")
  55. IF %ERRORLEVEL% EQU  4 (SET "preset=veryfast")
  56. IF %ERRORLEVEL% EQU  5 (SET "preset=faster")
  57. IF %ERRORLEVEL% EQU  6 (SET "preset=fast")
  58. IF %ERRORLEVEL% EQU  7 (SET "preset=medium")
  59. IF %ERRORLEVEL% EQU  8 (SET "preset=slow")
  60. IF %ERRORLEVEL% EQU  9 (SET "preset=slower")
  61. IF %ERRORLEVEL% EQU 10 (SET "preset=veryslow")
  62.  
  63. :: SET "forcedFPS=-r 23.976"
  64. CLS
  65.  
  66. "%~dp0ffmpeg.exe" %forcedFPS% -y -loglevel info -i "%~1" -c:v libx264 -preset %preset% -crf 23 -c:a aac -strict experimental -tune fastdecode -pix_fmt yuv420p -b:a 192k -ar 48000 %forcedFPS% "%~n1_VEGAS.mp4"
  67.  
  68. If %ERRORLEVEL% EQU 0 (
  69.    CLS
  70.    Color A
  71.    Echo+
  72.    Echo: Video conversion completed successfully.    | MORE | MORE
  73.    Echo: Input.: "%~1"                               | MORE
  74.    Echo: Output: "%~dpn1_VEGAS.mp4"                  | MORE
  75.    Echo+
  76.    Pause
  77.    Exit /B 0
  78. ) ELSE (
  79.    Color C
  80.    Echo+
  81.    Echo: Video conversion completed with errors.     | MORE | MORE
  82.    Echo: Input.: "%~1"                               | MORE
  83.    Echo: Output: "%~dpn1_VEGAS.mp4"                  | MORE
  84.    Echo+
  85.    Pause
  86.    Exit /B 1
  87. )
  88.  
13  Programación / Scripting / [APORTE] [PowerShell] IrfanView | Crop image files en: 4 Marzo 2024, 14:48 pm
El siguiente script desarrollado en PowerShell y dependiente del programa de terceros IrfanView, sirve para hacer un recorte (crop) específico en los archivos de imagen del directorio actual.

En la sección "Variables" dentro del script pueden personalizar los puntos de recorte (x, y, width, height), así como la calidad de codificación para archivos JPG entre otras cosas configurables.





Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $inputDirectoryPath = "$PSScriptRoot"
  10. $fileNameSearchPattern = "*.*"
  11. $imageExts = @("avif", "bmp", "jp2", "jpg", "png", "tga", "tif", "webp")
  12. $recurse = $false
  13.  
  14. $irfanviewFullPath = "C:\Program Files\IrfanView\i_view64.exe"
  15.  
  16. # Cropping values
  17. $x      = 12
  18. $y      = 20
  19. $width  = 620
  20. $height = 560
  21.  
  22. # For cropping images that are jpg/jpeg
  23. $jpgQuality = 95
  24.  
  25.  
  26. <#
  27. ===========================================================================================
  28. |                                                                                         |
  29. |                                    Functions                                            |
  30. |                                                                                         |
  31. ===========================================================================================
  32. #>
  33.  
  34. function Show-WelcomeScreen {
  35.    Clear-Host
  36.    Write-Host ""
  37.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  38.    Write-Host " +=========================================+"
  39.    Write-Host " |                                         |"
  40.    Write-Host " | This script will search for image files |"
  41.    Write-Host " | in the current working directory, and   |"
  42.    Write-Host " | use IrfanView to crop them using the    |"
  43.    Write-Host " | specified cropping settings.            |"
  44.    Write-Host " |                                         |"
  45.    Write-Host " +=========================================+"
  46.    Write-Host ""
  47.    Write-Host " Script Settings         " -ForegroundColor DarkGray
  48.    Write-Host " ========================" -ForegroundColor DarkGray
  49.    Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray
  50.    Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray
  51.    Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray
  52.    Write-Host " Search File Extensions..: $($imageExts -join ', ')" -ForegroundColor DarkGray
  53.    Write-Host " IrfanView Full Path.....: $irfanviewFullPath" -ForegroundColor DarkGray
  54.    Write-Host " JPG Quality.............: $jpgQuality%" -ForegroundColor DarkGray
  55.    Write-Host " Cropping.values.........: X=$x, Y=$y, Width=$width, Height=$height" -ForegroundColor DarkGray
  56.    Write-Host ""
  57. }
  58.  
  59. function Confirm-Continue {
  60.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  61.    Write-Host ""
  62.    Write-Host " -Continue? (Y/N)"
  63.    do {
  64.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  65.        $char = $key.Character.ToString().ToUpper()
  66.        if ($char -ne "Y" -and $char -ne "N") {
  67.            [console]::beep(1500, 500)
  68.        }
  69.    } while ($char -ne "Y" -and $char -ne "N")
  70.    if ($char -eq "N") {Exit(1)}
  71. }
  72.  
  73. function Validate-Parameters {
  74.  
  75.    if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) {
  76.        Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red
  77.        Write-Host ""
  78.        Write-Host " Press any key to exit..."
  79.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  80.        Exit(1)
  81.    }
  82.  
  83.    if (-not (Test-Path -LiteralPath $irfanviewFullPath -PathType Leaf)) {
  84.        Write-Host " Irfanview file path does not exists!" -BackgroundColor Black -ForegroundColor Red
  85.        Write-Host ""
  86.        Write-Host " Press any key to exit..."
  87.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  88.        Exit(1)
  89.    }
  90.  
  91.    if ($imageExts.Count -eq 0) {
  92.        Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red
  93.        Write-Host ""
  94.        Write-Host " Press any key to exit..."
  95.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  96.        Exit(1)
  97.    }
  98.  
  99. }
  100.  
  101. function Crop-Files {
  102.    Clear-Host
  103.  
  104.    $imageFiles = $null
  105.    if ($recurse) {
  106.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  107.    } else {
  108.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  109.    }
  110.  
  111.    foreach ($imageFile in $imageFiles) {
  112.        Write-Host " Cropping file: $($imageFile.FullName.Replace($inputDirectoryPath, "."))"
  113.  
  114.        $exitCode = $null
  115.        try {
  116.            $process = New-Object System.Diagnostics.Process
  117.            $process.StartInfo.FileName = $irfanviewFullPath
  118.            $process.StartInfo.Arguments = "`"$($imageFile.FullName)`" /crop=($x,$y,$width,$height) /jpgq=$jpgQuality /convert=""$($imageFile.FullName)"""
  119.            $process.StartInfo.UseShellExecute = $false
  120.            $started  = $process.Start() | Out-Null
  121.            $exited   = $process.WaitForExit()
  122.            $exitCode = $process.ExitCode
  123.        } catch {
  124.            Write-Host ""
  125.            Write-Host " Error running IrfanView process." -BackgroundColor Black -ForegroundColor Red
  126.            Write-Host ""
  127.            Write-Error -Message ($_.Exception.Message)
  128.            Write-Host ""
  129.            Write-Host " Press any key to exit..."
  130.            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  131.            Exit(1)
  132.        }
  133.  
  134.        if ($exitCode -eq 0) {
  135.            Write-Host " File cropped successfully." -ForegroundColor DarkGreen
  136.            Write-Host ""
  137.        } else {
  138.            Write-Host " Error cropping file. IrfanView Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red
  139.            Write-Host ""
  140.            Write-Host " Press any key to ignore and continue..."
  141.            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  142.        }
  143.    }
  144. }
  145.  
  146. function Show-GoodbyeScreen {
  147.    Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  148.    Write-Host ""
  149.    Write-Host " Press any key to exit..."
  150.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  151.    Exit(0)
  152. }
  153.  
  154. <#
  155. ===========================================================================================
  156. |                                                                                         |
  157. |                                         Main                                            |
  158. |                                                                                         |
  159. ===========================================================================================
  160. #>
  161.  
  162. [System.Console]::Title = "Crop image files - by Elektro"
  163. #[System.Console]::SetWindowSize(146, 27)
  164. [CultureInfo]::CurrentUICulture = "en-US"
  165.  
  166. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  167.  
  168. Show-WelcomeScreen
  169. Validate-Parameters
  170. Confirm-Continue
  171. Crop-Files
  172. Show-GoodbyeScreen
  173.  
14  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.





Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $inputDirectoryPath = "$PSScriptRoot"
  10. $fileNameSearchPattern = "*.*"
  11. $imageExts = @("avif", "bmp", "jp2", "jpg", "png", "tga", "tif", "webp")
  12. $recurse = $false
  13.  
  14. $irfanviewFullPath = "C:\Program Files\IrfanView\i_view64.exe"
  15. $jpgQuality = 95
  16. $overwriteConfirm = $true
  17. $sendToRecycleBinConvertedFiles = $true
  18.  
  19. <#
  20. ===========================================================================================
  21. |                                                                                         |
  22. |                                    Functions                                            |
  23. |                                                                                         |
  24. ===========================================================================================
  25. #>
  26.  
  27. function Show-WelcomeScreen {
  28.    Clear-Host
  29.    Write-Host ""
  30.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  31.    Write-Host " +===========================================+"
  32.    Write-Host " |                                           |"
  33.    Write-Host " | This script will search for image files   |"
  34.    Write-Host " | in the current working directory, and use |"
  35.    Write-Host " | IrfanView to convert them to JPG format.  |"
  36.    Write-Host " |                                           |"
  37.    Write-Host " +===========================================+"
  38.    Write-Host ""
  39.    Write-Host " Script Settings         " -ForegroundColor DarkGray
  40.    Write-Host " ========================" -ForegroundColor DarkGray
  41.    Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray
  42.    Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray
  43.    Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray
  44.    Write-Host " Search File Extensions..: $($imageExts -join ', ')" -ForegroundColor DarkGray
  45.    Write-Host " IrfanView Full Path.....: $irfanviewFullPath" -ForegroundColor DarkGray
  46.    Write-Host " JPG Quality.............: $jpgQuality%" -ForegroundColor DarkGray
  47.    Write-Host " Confirm Overwrite JPG...: $overwriteConfirm" -ForegroundColor DarkGray
  48.    Write-Host " Recycle Converted Files.: $sendToRecycleBinConvertedFiles" -ForegroundColor DarkGray
  49.    Write-Host ""
  50. }
  51.  
  52. function Confirm-Continue {
  53.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  54.    Write-Host ""
  55.    Write-Host " -Continue? (Y/N)"
  56.    do {
  57.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  58.        $char = $key.Character.ToString().ToUpper()
  59.        if ($char -ne "Y" -and $char -ne "N") {
  60.            [console]::beep(1500, 500)
  61.        }
  62.    } while ($char -ne "Y" -and $char -ne "N")
  63.    if ($char -eq "N") {Exit(1)}
  64. }
  65.  
  66. function Validate-Parameters {
  67.  
  68.    if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) {
  69.        Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red
  70.        Write-Host ""
  71.        Write-Host " Press any key to exit..."
  72.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  73.        Exit(1)
  74.    }
  75.  
  76.    if (-not (Test-Path -LiteralPath $irfanviewFullPath -PathType Leaf)) {
  77.        Write-Host " Irfanview file path does not exists!" -BackgroundColor Black -ForegroundColor Red
  78.        Write-Host ""
  79.        Write-Host " Press any key to exit..."
  80.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  81.        Exit(1)
  82.    }
  83.  
  84.    if ($imageExts.Count -eq 0) {
  85.        Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red
  86.        Write-Host ""
  87.        Write-Host " Press any key to exit..."
  88.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  89.        Exit(1)
  90.    }
  91.  
  92. }
  93.  
  94. function Convert-Files {
  95.    Clear-Host
  96.    Add-Type -AssemblyName Microsoft.VisualBasic
  97.  
  98.    $imageFiles = $null
  99.    if ($recurse) {
  100.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  101.    } else {
  102.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') }
  103.    }
  104.  
  105.    foreach ($imageFile in $imageFiles) {
  106.        Write-Host " Converting to JPG: $($imageFile.FullName.Replace($inputDirectoryPath, "."))"
  107.  
  108.        $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($imageFile.Name)
  109.        $outputFilePath = Join-Path -Path ($imageFile.Directory.FullName) -ChildPath "$fileNameWithoutExtension.jpg"
  110.  
  111.        if ((Test-Path -LiteralPath $outputFilePath -PathType Leaf) -and ($overwriteConfirm)) {
  112.            # El archivo no existe o no se debe sobrescribir
  113.            Write-Warning " Output JPG file already exists but `$overwriteConfirm variable is disabled."
  114.            Write-Warning " The output JPG file will be overwitten if you continue."
  115.            Write-Host ""
  116.            Confirm-Continue
  117.            Write-Host ""
  118.        }
  119.  
  120.        $exitCode = $null
  121.        try {
  122.            $procStartInfo = New-Object System.Diagnostics.ProcessStartInfo
  123.            $procStartInfo.FileName = $irfanviewFullPath
  124.            $procStartInfo.Arguments = "`"$($imageFile.FullName)`" /jpgq=$jpgQuality /convert=`"$outputFilePath`""
  125.            $procStartInfo.UseShellExecute = $false
  126.            $process = New-Object System.Diagnostics.Process
  127.            $process.StartInfo = $procStartInfo
  128.            $process.Start() | Out-Null
  129.            $process.WaitForExit()
  130.            $exitCode = $process.ExitCode
  131.        } catch {
  132.            Write-Host ""
  133.            Write-Host " Error running IrfanView process." -BackgroundColor Black -ForegroundColor Red
  134.            Write-Host ""
  135.            Write-Error -Message ($_.Exception.Message)
  136.            Write-Host ""
  137.            Write-Host " Press any key to exit..."
  138.            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  139.            Exit(1)
  140.        }
  141.  
  142.        if ($exitCode -eq 0) {
  143.            Write-Host " File converted successfully." -ForegroundColor DarkGreen
  144.            if ($sendToRecycleBinConvertedFiles) {
  145.                [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($imageFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  146.                Write-Host " File sent to recycle bin." -ForegroundColor DarkGray
  147.            }
  148.            Write-Host ""
  149.        } else {
  150.            Write-Host " Error converting file to JPG. IrfanView Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red
  151.            Write-Host ""
  152.        }
  153.    }
  154. }
  155.  
  156. function Show-GoodbyeScreen {
  157.    Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  158.    Write-Host ""
  159.    Write-Host " Press any key to exit..."
  160.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  161.    Exit(0)
  162. }
  163.  
  164. <#
  165. ===========================================================================================
  166. |                                                                                         |
  167. |                                         Main                                            |
  168. |                                                                                         |
  169. ===========================================================================================
  170. #>
  171.  
  172. [System.Console]::Title = "Convert image files to JPG - by Elektro"
  173. #[System.Console]::SetWindowSize(146, 27)
  174. [CultureInfo]::CurrentUICulture = "en-US"
  175.  
  176. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  177.  
  178. Show-WelcomeScreen
  179. Validate-Parameters
  180. Confirm-Continue
  181. Convert-Files
  182. Show-GoodbyeScreen
  183.  
  184.  
15  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.





Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $inputDirectoryPath = "$PSScriptRoot"
  10. $recurse = $true
  11. $fileSearchExts = @("avif", "bmp", "jp2", "jpg", "jpeg", "png", "tga", "tif", "webp")
  12. $fileNameSearchPattern = "*.*"
  13. #$fileNameSearchPattern = "Cover.*"
  14.  
  15. $iconSizes     = @(256, 128, 96, 64, 48, 32, 24, 16)
  16. $iconBackColor = "transparent"
  17. $iconQuality   = 100
  18.  
  19. $imageMagickFullPath = "$PSScriptRoot\magick.exe"
  20.  
  21. $imageMagickArgs     = @("-define icon:auto-resize=`"$($iconSizes -join ',')`"",
  22.                         "-background $iconBackColor",
  23.                         "-gravity center",
  24.                         "-extent 1:1#",
  25.                         "-quality $iconQuality"
  26.                        )
  27.  
  28. $overwriteConfirm = $true
  29. $sendToRecycleBinConvertedFiles = $false
  30.  
  31. <#
  32. ===========================================================================================
  33. |                                                                                         |
  34. |                                    Functions                                            |
  35. |                                                                                         |
  36. ===========================================================================================
  37. #>
  38.  
  39. function Show-WelcomeScreen {
  40.    Clear-Host
  41.    Write-Host ""
  42.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  43.    Write-Host " +=============================================+"
  44.    Write-Host " |                                            |"
  45.    Write-Host " | This script will search for image files    |"
  46.    Write-Host " | in the current working directory, and use  |"
  47.    Write-Host " | ImageMagick to convert them to ICO format. |"
  48.    Write-Host " |                                            |"
  49.    Write-Host " +============================================+"
  50.    Write-Host ""
  51.    Write-Host " Script Settings         " -ForegroundColor DarkGray
  52.    Write-Host " ========================" -ForegroundColor DarkGray
  53.    Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray
  54.    Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray
  55.    Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray
  56.    Write-Host " Search File Extensions..: $($fileSearchExts -join ', ')" -ForegroundColor DarkGray
  57.    Write-Host " ImageMagick Full Path...: $imageMagickFullPath" -ForegroundColor DarkGray
  58.    Write-Host " Icon Sizes (and order)..: $($iconSizes -join ', ')" -ForegroundColor DarkGray
  59.    Write-Host " Icon Background Color...: $iconBackColor" -ForegroundColor DarkGray
  60.    Write-Host " Icon Quality............: $iconQuality" -ForegroundColor DarkGray
  61.    Write-Host " Confirm Overwrite ICO...: $overwriteConfirm" -ForegroundColor DarkGray
  62.    Write-Host " Recycle Converted Files.: $sendToRecycleBinConvertedFiles" -ForegroundColor DarkGray
  63.    # Write-Host " ImageMagick Arguments...: $($imageMagickArgs -join $([Environment]::NewLine) + '                           ')" -ForegroundColor DarkGray
  64.    Write-Host ""
  65. }
  66.  
  67. function Confirm-Continue {
  68.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  69.    Write-Host ""
  70.    Write-Host " -Continue? (Y/N)"
  71.    do {
  72.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  73.        $char = $key.Character.ToString().ToUpper()
  74.        if ($char -ne "Y" -and $char -ne "N") {
  75.            [console]::beep(1500, 500)
  76.        }
  77.    } while ($char -ne "Y" -and $char -ne "N")
  78.    if ($char -eq "N") {Exit(1)}
  79. }
  80.  
  81. function Validate-Parameters {
  82.  
  83.    if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) {
  84.        Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red
  85.        Write-Host ""
  86.        Write-Host " Press any key to exit..."
  87.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  88.        Exit(1)
  89.    }
  90.  
  91.    if (-not (Test-Path -LiteralPath $imageMagickFullPath -PathType Leaf)) {
  92.        Write-Host " ImageMagick file path does not exists!" -BackgroundColor Black -ForegroundColor Red
  93.        Write-Host ""
  94.        Write-Host " Press any key to exit..."
  95.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  96.        Exit(1)
  97.    }
  98.  
  99.    if ([string]::IsNullOrEmpty($fileNameSearchPattern)) {
  100.        Write-Host " `$fileNameSearchPattern variable is null!" -BackgroundColor Black -ForegroundColor Red
  101.        Write-Host ""
  102.        Write-Host " Press any key to exit..."
  103.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  104.        Exit(1)
  105.    }
  106.  
  107.    if ($fileSearchExts.Count -eq 0) {
  108.        Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red
  109.        Write-Host ""
  110.        Write-Host " Press any key to exit..."
  111.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  112.        Exit(1)
  113.    }
  114.  
  115. }
  116.  
  117. function Convert-Files {
  118.    Clear-Host
  119.    Add-Type -AssemblyName Microsoft.VisualBasic
  120.  
  121.    $imageFiles = $null
  122.    if ($recurse) {
  123.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $fileSearchExts -contains $_.Extension.ToLower().TrimStart('.') }
  124.    } else {
  125.        $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $fileSearchExts -contains $_.Extension.ToLower().TrimStart('.') }
  126.    }
  127.  
  128.    foreach ($imageFile in $imageFiles) {
  129.        Write-Host " Converting to ICO: $($imageFile.FullName.Replace($inputDirectoryPath, "."))"
  130.  
  131.        $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($imageFile.Name)
  132.        $outputFilePath = Join-Path -Path ($imageFile.Directory.FullName) -ChildPath "$fileNameWithoutExtension.ico"
  133.  
  134.        if ((Test-Path -LiteralPath $outputFilePath -PathType Leaf) -and ($overwriteConfirm)) {
  135.            # El archivo no existe o no se debe sobrescribir
  136.            Write-Warning " Output ICO file already exists but `$overwriteConfirm variable is disabled."
  137.            Write-Warning " The output ICO file will be overwitten if you continue."
  138.            Write-Host ""
  139.            Confirm-Continue
  140.            Write-Host ""
  141.        }
  142.  
  143.        $exitCode = $null
  144.        try {
  145.            $procStartInfo = New-Object System.Diagnostics.ProcessStartInfo
  146.            $procStartInfo.FileName = $imageMagickFullPath
  147.            $procStartInfo.Arguments = "`"$($imageFile.FullName)`" $($imageMagickArgs -join ' ') `"$outputFilePath`""
  148.            $procStartInfo.UseShellExecute = $false
  149.            $process = New-Object System.Diagnostics.Process
  150.            $process.StartInfo = $procStartInfo
  151.            $process.Start() | Out-Null
  152.            $process.WaitForExit()
  153.            $exitCode = $process.ExitCode
  154.        } catch {
  155.            Write-Host ""
  156.            Write-Host " Error running ImageMagick process." -BackgroundColor Black -ForegroundColor Red
  157.            Write-Host ""
  158.            Write-Error -Message ($_.Exception.Message)
  159.            Write-Host ""
  160.            Write-Host " Press any key to exit..."
  161.            $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  162.            Exit(1)
  163.        }
  164.  
  165.        if ($exitCode -eq 0) {
  166.            Write-Host " File converted successfully." -ForegroundColor DarkGreen
  167.            if ($sendToRecycleBinConvertedFiles) {
  168.                [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($imageFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  169.                Write-Host " File sent to recycle bin." -ForegroundColor DarkGray
  170.            }
  171.            Write-Host ""
  172.        } else {
  173.            Write-Host " Error converting file to ICO. ImageMagick Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red
  174.            Write-Host ""
  175.        }
  176.    }
  177. }
  178.  
  179. function Show-GoodbyeScreen {
  180.    Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  181.    Write-Host ""
  182.    Write-Host " Press any key to exit..."
  183.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  184.    Exit(0)
  185. }
  186.  
  187. <#
  188. ===========================================================================================
  189. |                                                                                         |
  190. |                                         Main                                            |
  191. |                                                                                         |
  192. ===========================================================================================
  193. #>
  194.  
  195. [System.Console]::Title = "Convert image files to ICO - by Elektro"
  196. #[System.Console]::SetWindowSize(146, 27)
  197. [CultureInfo]::CurrentUICulture = "en-US"
  198.  
  199. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  200.  
  201. Show-WelcomeScreen
  202. Validate-Parameters
  203. Confirm-Continue
  204. Convert-Files
  205. Show-GoodbyeScreen
  206.  
16  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.
17  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
18  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)
19  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)
20  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.  
Páginas: 1 [2] 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ... 105
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines