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

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


  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] 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.  
112  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.  
113  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.  
114  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.  
115  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.
116  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!.
117  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
118  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)
119  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)
120  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.
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