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


Tema destacado: Tutorial básico de Quickjs


  Mostrar Temas
Páginas: 1 2 3 [4] 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... 107
31  Sistemas Operativos / Windows / [SOLUCIONADO] Busco algún programa cuyo instalador genere este tipo de archivo link... en: 5 Marzo 2024, 13:18 pm
Buenos días. No se si publicar esta solicitud aquí o en el foro libre (o tal vez en Software).

Yo lo veo más relacionado con aspectos relacionados con Windows, pero muévanlo donde prefieran.

El caso es que tengo la necesidad de encontrar algún software que se distribuya en forma de instalador, y que al momento de instalar dicho software se genere un acceso directo como el de la siguiente imagen, donde no se permite la modificación de la propiedad "Destino":



(lo siento por el idioma de la imagen XD)

Esa restricción a la hora de modificar el destino, se debe a que el acceso directo fue creado usando un identificador especial del sistema en lugar de haber utilizado una cadena de texto convencional ( más info: learn.microsoft.com - Item IDs ), y al parecer Windows deshabilita la caja de texto de la propiedad "Destino" para ese tipo de links que fueron creados de tal forma.

Bueno, pues no se me ocurre donde puedo encontrar y descargar un software / instalador que genere ese tipo de archivo de acceso directo (*.lnk). Me da igual si el programa es gratuito o de pago, es simplemente que me permita instalarlo y me genere ese archivo link para cuestiones de prueba en un entorno de programación.



Es evidente, por la imagen que he compartido, que el Microsoft Word al parecer genera ese tipo de archivo link, pero a mi me han pasado una ISO del Office 2016 de 2 GB, y a mi no me genera ese link. Quizás no estoy usando la ISO correcta.

Tengo conocimiento de que el emulador de video juegos por nombre "Yuzu", o tal vez era otro por nombre "Citra", creaban este tipo de archivo link, pero para mi mala suerte justo ayer cerraron sus sitios web (debido a una demanda por parte de la compañía Nintendo) y el instalador ya no funciona por que requiere acceso online.

Ahora no recuerdo otro programa que genere ese tipo de acceso directo. Se supone que hay aplicación de la Microsoft Store que cuando se instalan generan ese tipo de link, pero yo tengo la Microsoft Store capada de mi instalación de Windows. También se supone que hay video juegos que generan ese tipo de link en la carpeta integrada "Juegos" del menú inicio, pero esto también lo tengo parcialmente capado y de todas formas no se si habrá algún juego gratuito con el que probar a ver.

Gracias con antelación.
32  Programación / Scripting / [APORTE] [PowerShell] SetACL.exe | Get Full Registry Ownership en: 4 Marzo 2024, 15:31 pm
El siguiente script desarrollado en PowerShell y dependiente del programa de terceros SetACL (https://helgeklein.com/download/#), sirve para adquirir propiedad absoluta sobre todas las claves de registro del sistema, lo que puede servir en algunos escenarios de prueba (generalmente en máquinas virtuales), o de infecciones por malware.

UTILIZAR ESTE SCRIPT BAJO SU PROPIA RESPONSABILIDAD, Y BAJO UNA CUENTA DE ADMINISTRADOR.

MODIFICAR LOS PERMISOS DE ALGUNAS CLAVES DEL REGISTRO DE WINDOWS PUEDE CONLLEVAR CONSECUENCIAS IMPREVISTAS QUE PROVOQUEN UN MALFUNCIONAMIENTO DEL SISTEMA OPERATIVO E IMPIDAN INICIAR SESIÓN DE USUARIO.

NO ME HAGO RESPONSABLE DE NADA.






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 take the ownership and ACE (Access Control Entry) |"
  16.    Write-Output " | of all the registry keys and subkeys in the current computer,      |"
  17.    Write-Output " | giving full access and permissions for the current user.           |"
  18.    Write-Output " |                                                                    |"
  19.    Write-Output " +====================================================================+"
  20.    Write-Output ""
  21.    Write-Host   " CHANGING THE OWNER AND PERMISSIONS COULD BREAK THINGS," -ForegroundColor Red
  22.    Write-Host   " SO PROCEED WITH CAUTION AND DO IT AT YOUR OWN RISK !!" -ForegroundColor Red
  23.    Write-Output ""
  24.    Write-Output " CURRENT SCRIPT CONFIG:"
  25.    Write-Output " ----------------------"
  26.    Write-Output " -SetAclFilePath: $SetAclFilePath"
  27.    Write-Output " -UserName......: $UserName"
  28.    Write-Output " -RegKeys.......:"
  29.    Write-Output ($RegKeys | ForEach-Object {"                  $_"})
  30.    Write-Output ""
  31. }
  32.  
  33. function Confirm-Continue {
  34.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  35.    Write-Host ""
  36.    Write-Host " -Continue? (Y/N)"
  37.    do {
  38.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  39.        $char = $key.Character.ToString().ToUpper()
  40.        if ($char -ne "Y" -and $char -ne "N") {
  41.            [console]::beep(1500, 500)
  42.        }
  43.    } while ($char -ne "Y" -and $char -ne "N")
  44.    if ($char -eq "N") {Exit(1)} else {Clear-Host}
  45. }
  46.  
  47. function Get-RegistryOwnership {
  48.    param(
  49.        [string]$setAclFilePath = "$env:ProgramFiles\SetACL\setacl.exe",
  50.        [string[]]$regKeys,
  51.        [string]$userName = "$env:UserName"
  52.    )
  53.  
  54.    try {
  55.        if (-not (Test-Path $setAclFilePath)) {
  56.            $ex = New-Object System.IO.FileNotFoundException("SetACL.exe file not found at path '$setAclFilePath'.", $setAclFilePath)
  57.            throw $ex
  58.        }
  59.  
  60.        $logFile = New-TemporaryFile
  61.  
  62.        foreach ($key in $regKeys) {
  63.            Start-Process -Wait -FilePath "$setAclFilePath" -ArgumentList "-on", "`"$key`"", "-ot", "reg", "-actn", "setowner", "-ownr", "`"n:$userName`"", "-rec", "Yes", "-actn", "ace", "-ace", "`"n:$userName;p:full`"", "-rec", "Yes", "-log", "`"$($logFile.FullName)`"" -NoNewWindow -PassThru
  64.            #$logContent = Get-Content -Path $logFile.FullName
  65.            Write-Output ""
  66.            #Write-Output $logContent
  67.        }
  68.  
  69.    } catch {
  70.        Write-Host "Something went wrong when calling '$($MyInvocation.MyCommand.Name)' method:"
  71.        Write-Host ""
  72.        Write-Warning ($_.Exception)
  73.        Write-Host ""
  74.        Write-Error -Message ($_.Exception | Format-List * -Force | Out-String)
  75.        Write-Host ""
  76.        Write-Host "Press any key to exit..."
  77.        $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  78.        Exit(1)
  79.    }
  80. }
  81.  
  82. function Show-GoodbyeScreen {
  83.    Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  84.    Write-Host ""
  85.    Write-Host "Press any key to exit..."
  86.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  87.    Exit(0)
  88. }
  89.  
  90. <#
  91. ===========================================================================================
  92. |                                                                                         |
  93. |                                         Main                                            |
  94. |                                                                                         |
  95. ===========================================================================================
  96. #>
  97.  
  98. [System.Console]::Title = "Get Full Registry Ownership Tool - by Elektro"
  99. [CultureInfo]::CurrentUICulture = "en-US"
  100.  
  101. $SetAclFilePath = "$env:ProgramFiles\SetACL\SetACL.exe"
  102. $RegKeys = "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CURRENT_CONFIG"
  103. $UserName = $env:UserName
  104.  
  105. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  106.  
  107. Show-WelcomeScreen
  108. Confirm-Continue
  109. Get-RegistryOwnership -SetAclFilePath $SetAclFilePath -RegKeys $RegKeys -UserName $UserName
  110. Show-GoodbyeScreen
33  Programación / Scripting / [APORTE] [PowerShell] Automated AppX Package Installer en: 4 Marzo 2024, 15:19 pm
El siguiente script desarrollado en Powershell, buscará archivos de paquetes AppX (*.appx, *.appxbundle, *.msixbundle) dentro del directorio actual (sin recursividad), imprimirá información sobre el paquete, imprimirá un mensaje en caso de que el paquete ya esté instalado, e instalará el paquete en caso de que no esté instalado, manejando posibles errores durante instalación.

Es una herramienta muy útil en particular para quien (como yo) tenga completamente capada la Microsoft Store y sus funcionalidades en el sistema operativo, y necesite una forma de poder instalar paquetes de aplicaciones (*.appx, *.appxbundle, *.msixbundle) descargadas de forma local desde la Microsoft Store.





Código
  1. # --------------------------------------------- #
  2. # Automated AppX Package Installer - by Elektro #
  3. # --------------------------------------------- #
  4.  
  5. # This script will find any AppX package files within the current directory (without recursion),
  6. # print info about the package, print a message in case of the package is already installed,
  7. # and install the package in case of it is not installed, handling errors during installation.
  8.  
  9. # ---------------------------------------------------------------------
  10.  
  11. # Takes a string argument that points to an AppX package name or file,
  12. # then it uses a regular expression to match the package string pattern
  13. # and returns a custom object with the Name, Version, Architecture,
  14. # PublisherId and other properties.
  15. #
  16. # Parameters:
  17. #   -PackageString: A string that points to the file name
  18. #                   or full path of an AppX package file.
  19. #
  20. # Returns:
  21. #   A PSCustomObject object with these properties defined:
  22. #     [String] Name
  23. #     [String] Version
  24. #     [String] Architecture
  25. #     [String] PublisherId
  26. #     [String] FullName
  27. function Get-AppXPackageInfo {
  28.    param (
  29.        [Parameter(Mandatory=$true)] [string]$PackageString
  30.    )
  31.  
  32.    #$dirname = [System.IO.Path]::GetDirectoryName($PackageString)
  33.    #if ([string]::IsNullOrEmpty($dirname)) {
  34.    #    $dirname = $PWD
  35.    #}
  36.  
  37.    $filename = [System.IO.Path]::GetFileName($PackageString) -replace "(?i)\.appxbundle$", "" -replace "(?i)\.msixbundle$", "" -replace "(?i)\.appx$", ""
  38.  
  39.    $regex = '^(?<Name>.+?)_(?<Version>.+?)_(?<Architecture>.+?)_(?<chars>~)?_(?<PublisherId>.+)$'
  40.    $match = $filename -match $regex
  41.  
  42.    if (!$match) {
  43.        throw "Unable to parse the string package: '$PackageString'"
  44.    }
  45.  
  46.    [string]$packageName         = $matches['Name']
  47.    [string]$packageVersion      = $matches['Version']
  48.    [string]$packageArchitecture = $matches['Architecture']
  49.    [string]$packagePublisherId  = $matches['PublisherId']
  50.    [string]$chars               = $matches['chars']
  51.    [string]$packageFullName     = "${packageName}_${packageVersion}_${packageArchitecture}_${chars}_${packagePublisherId}"
  52.    #[string]$packageFullPath    = [System.IO.Path]::Combine($dirname, "$filename.Appx")
  53.  
  54.    [PSCustomObject]@{
  55.        Name = $packageName
  56.        Version = $packageVersion
  57.        Architecture = $packageArchitecture
  58.        PublisherId = $packagePublisherId
  59.        FullName = $packageFullName
  60.        #FullPath = $packageFullPath
  61.    }
  62. }
  63.  
  64. # Determines whether an Appx package matching the specified
  65. # name, version and architecture is installed in the system.
  66. #
  67. # Parameters:
  68. #   -Name........: The package name.
  69. #   -Version.....: The package version.
  70. #   -Architecture: The package architecture ("x86", "x64").
  71. #
  72. # Returns:
  73. #   $true if the AppX package is installed in the system,
  74. #   $false otherwise.
  75. function IsAppxPackageInstalled() {
  76.    param (
  77.        [Parameter(Mandatory=$true)] [string]$name,
  78.        [Parameter(Mandatory=$true)] [string]$version,
  79.        [Parameter(Mandatory=$true)] [string]$architecture
  80.    )
  81.  
  82.    if ($architecture -eq "neutral") {
  83.        $architecture = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture
  84.    }
  85.  
  86.    $packages = Get-AppxPackage "$($name)*" -ErrorAction Stop | Where-Object {
  87.        $_.Name.ToLower()              -eq $name.ToLower()         -and
  88.        $_.Version.ToLower()           -eq $version.ToLower()      -and
  89.        "$($_.Architecture)".ToLower() -eq $architecture.ToLower()
  90.    }
  91.    return ($packages.Count -gt 0)
  92. }
  93.  
  94. <#
  95. ===========================================================================================
  96. |                                                                                         |
  97. |                                         Main                                            |
  98. |                                                                                         |
  99. ===========================================================================================
  100. #>
  101.  
  102. [System.Console]::Title = "Automated AppX Package Installer - by Elektro"
  103. [CultureInfo]::CurrentUICulture = "en-US"
  104.  
  105. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  106.  
  107. # Hides the progress-bar for 'Add-AppxPackage' cmdlet in this script.
  108. # Thanks to @Santiago Squarzon for the tip: https://stackoverflow.com/questions/75716867
  109. # https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.3#progresspreference
  110. $ProgressPreference = "Ignore"
  111.  
  112. Do {
  113.    Clear-Host
  114.    Write-Output ""
  115.    Write-Output " $($host.ui.RawUI.WindowTitle)"
  116.    Write-Output " +=====================================================+"
  117.    Write-Output " |                                                     |"
  118.    Write-Output " | This script will find any AppX package files        |"
  119.    Write-Output " | within the current directory (without recursion),   |"
  120.    Write-Output " | print info about the package, print a message       |"
  121.    Write-Output " | in case of the package is already installed,        |"
  122.    Write-Output " | and install the package in case of it is            |"
  123.    Write-Output " | not installed, handling errors during installation. |"
  124.    Write-Output " |                                                     |"
  125.    Write-Output " +=====================================================+"
  126.    Write-Output ""
  127.    Write-Host " -Continue? (Y/N)"
  128.    $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  129.    $char = $key.Character.ToString().ToUpper()
  130.    if ($char -ne "Y" -and $char -ne "N") {
  131.        [console]::beep(1500, 500)
  132.    }
  133. } while ($char -ne "Y" -and $char -ne "N")
  134. if ($char -eq "N") {Exit(1)} else {Clear-Host}
  135.  
  136. $appxFiles = Get-ChildItem -Path "$PWD" -Filter "*.appx*"
  137.  
  138. if ($appxFiles.Count -eq 0) {
  139.    Write-Warning "No Appx files were found in the current directory."
  140.    Write-Host ""
  141.    $LastExitCode = 2
  142. } else {
  143.    $appxFiles | ForEach-Object {
  144.        # The AppX package string. It can be a file name (with or without extension), or a full path.
  145.        $packageString = $_.FullName
  146.        $packageInfo = Get-AppXPackageInfo -PackageString $packageString
  147.        $nameVerArch = "$($packageInfo.Name) v$($packageInfo.Version) ($($packageInfo.Architecture))"
  148.        Write-Host "Package Info.:" -ForegroundColor Gray
  149.        Write-Host ($packageInfo | Format-List | Out-String).Trim() -ForegroundColor DarkGray
  150.        Write-Host ""
  151.  
  152.        $isInstalled = IsAppxPackageInstalled -Name $packageInfo.Name -Version $packageInfo.Version -Architecture $packageInfo.Architecture
  153.        if ($isInstalled) {
  154.            Write-Warning "Package $nameVerArch is already installed."
  155.            Write-Warning "Installation is not needed."
  156.        } else {
  157.            Write-Host "Package $nameVerArch is ready to install."
  158.            Write-Host "Installing package..."
  159.            try {
  160.                Add-AppxPackage -Path "$($_.FullName)" -ErrorAction Stop
  161.                Write-Host "Package $nameVerArch has been successfully installed." -BackgroundColor Black -ForegroundColor Green
  162.            } catch {
  163.                Write-Host "Error installing package $nameVerArch" -BackgroundColor Black -ForegroundColor Red
  164.                Write-Host ""
  165.                Write-Error -Message ($_.Exception | Format-List * -Force | Out-String)
  166.                $LastExitCode = 1
  167.                Break
  168.            }
  169.        }
  170.        Write-Host ""
  171.        $LastExitCode = 0
  172.    }
  173. }
  174.  
  175. Write-Host "Program will terminate now with exit code $LastExitCode. Press any key to exit..."
  176. $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  177. Exit($LastExitCode)
34  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. #>
35  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.  
36  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.  
37  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.  
38  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.  
39  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.
40  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
Páginas: 1 2 3 [4] 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... 107
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines