| |
|
31
|
Programación / Scripting / [APORTE] [VBS] VMWare: Mount / Unmount Shared Folders Network Drive
|
en: 19 Marzo 2024, 00:52 am
|
Los siguientes dos scripts, desarrollados en el lenguaje Visual Basic Script y que se deben usar en conjunto con una máquina virtual de VMWare (aunque se pueden modificar para Virtual Box), sirven como atajo para montar y desmontar la unidad de red de las "carpetas compartidas" (shared folders). Utilizar estos scripts nos ahorra un valioso tiempo al no tener que usar el cliente de VMWare para abrir el menú de opciones donde desactivar y reactivar las carpetas compartidas. La idea tras esta simple herramienta es eso, ahorrar tiempo, y de esta manera poder aislar la máquina virtual del sistema operativo anfitrión impidiendo el acceso a la unidad de red de las carpetas compartidas, y volver a habilitar el acceso, tan solo haciendo dos clicks para ejecutar estos scripts. Mount Shared Folders Network Drive.vbs' Mount VMWare Shared Folders Network Drive Option Explicit Dim objFSO, objShell, objNetwork, colDrives, colNetDrives, i, msg Dim objDrive, vmWareDrive, vmWarePath, drive, path vmWareDrive = "Z:" vmWarePath = "\\vmware-host\Shared Folders" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("WScript.Shell") Set objNetwork = CreateObject("WScript.Network") Set colDrives = objFSO.Drives Set colNetDrives = objNetwork.EnumNetworkDrives For i = 0 to colNetDrives.Count - 1 Step 2 drive = colNetDrives.Item(i) path = colNetDrives.Item(i+1) If (LCase(drive) = LCase(vmWareDrive)) Then If (LCase(path) = LCase(vmWarePath)) Then msg = "A network drive is already mounted with same letter and UNC path:" & vbCrLf & vbCrLf msg = msg & drive & vbTab & """" & path & """" objShell.Popup msg, 20, "Warning: Network Drives", 48 Else msg = "A network drive is already mounted with a different UNC path:" & vbCrLf & vbCrLf msg = msg & drive & vbTab & """" & path & """" objShell.Popup msg, 20, "Error: Network Drives", 16 End If WScript.Quit() End If Next For Each objDrive in colDrives drive = objDrive.DriveLetter & ":" If (LCase(drive) = LCase(vmWareDrive)) Then msg = "A local drive is already mounted with the same drive letter:" & vbCrLf & vbCrLf msg = msg & "Letter: " & drive & vbCrLf msg = msg & "FileSystem: " & objDrive.FileSystem & vbCrLf msg = msg & "Volume Name: " & objDrive.VolumeName & vbCrLf msg = msg & "Share Name: " & objDrive.ShareName objShell.Popup msg, 20, "Error: Network Drives", 16 WScript.Quit() End If Next objNetwork.MapNetworkDrive vmWareDrive, vmWarePath msg = "The following network drive was successfully mounted:" & vbCrLf & vbCrLf msg = msg & vmWareDrive & vbTab & """" & vmWarePath & """" objShell.Popup msg, 20, "Info: Network Drives", 64 WScript.Quit()
Unmount Shared Folders Network Drive.vbs' Unmount VMWare Shared Folders Network Drive Option Explicit Dim objShell, objNetwork, colDrives, i, msg Dim vmWareDrive, vmWarePath, drive, path vmWareDrive = "Z:" vmWarePath = "\\vmware-host\Shared Folders" Set objShell = CreateObject("WScript.Shell") Set objNetwork = CreateObject("WScript.Network") Set colDrives = objNetwork.EnumNetworkDrives For i = 0 to colDrives.Count - 1 Step 2 drive = colDrives.Item(i) path = colDrives.Item(i+1) If (LCase(drive) = LCase(vmWareDrive)) Then If (LCase(path) = LCase(vmWarePath)) Then objNetwork.RemoveNetworkDrive vmWareDrive, True, True msg = "The following network drive was successfully unmounted:" & vbCrLf & vbCrLf msg = msg & drive & vbTab & """" & path & """" objShell.Popup msg, 20, "Info: Network Drives", 64 Else msg = "A network drive is already mounted with a different UNC path:" & vbCrLf & vbCrLf msg = msg & drive & vbTab & """" & path & """" objShell.Popup msg, 20, "Warning: Network Drives", 16 End If WScript.Quit() End If Next msg = "No matching network drive " & """" & vmWareDrive & """" & " was found." objShell.Popup msg, 20, "Error: Network Drives", 16 WScript.Quit()
|
|
|
|
|
32
|
Media / Juegos y Consolas / Emuladores Yuzu y Citra: Aquí puedes descargar sus últimas versiones.
|
en: 5 Marzo 2024, 13:59 pm
|
No me andaré con muchos rodeos, simplemente mencionaré lo importante para dar contexto, y es que Nintendo demandó a los creadores del emulador Yuzu para Nintendo Switch, que también son los creadores del emulador Citra para Nintendo 3DS, y desde aproximadamente el día 04/Marzo/2024 han desaparecido los repositorios de código abierto para ambos emuladores, y con ello, los enlaces de descarga a los emuladores. En este hilo compartiré el método a llevar a cabo para que puedan descargar las últimas releases públicadas para ambos emuladores. El contenido ofrecido en este hilo no es ilegal, son (eran) programas de código abierto con un gran apoyo por parte de su comunidad y reseñas en todo tipo de medios oficiales, además, en este hilo no se comparten descargas directas, y por supuesto el hecho de que una compañía demande a un individuo para preservar sus intereses comerciales eso ni por asomo lo convierte en una acción delictiva per se.De todas formas y si a pesar de ello el staff considera que es mejor no publicar este tipo de contenido, no pondré objeción y pido disculpas, por supuesto.
La metodología consiste en usar la Wayback Machine de Internet Archive para acceder a la copia estática más reciente de los repositorios de ambos emuladores con sus correspondientes descargas:  (Para Windows deben descargar el archivo con extensión .zip, ya que no hay copia disponible para el archivo .7z y .tar.xz)  La compilación Nightly se basa en la rama maestra y contiene funciones ya revisadas y probadas.
La compilación Canary se basa en la rama maestra, pero aún se están revisando características adicionales.
Eso sería todo. ¡Disfrútenlo mientras todavía se pueda! (mientras Nintendo no decida seguir arruinando más su imagen demandando a los de archive.org ).Aténtamente, Elektro.
|
|
|
|
|
33
|
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.
|
|
|
|
|
34
|
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.
<# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Output "" Write-Output " $($host.ui.RawUI.WindowTitle)" Write-Output " +====================================================================+" Write-Output " | |" Write-Output " | This script will take the ownership and ACE (Access Control Entry) |" Write-Output " | of all the registry keys and subkeys in the current computer, |" Write-Output " | giving full access and permissions for the current user. |" Write-Output " | |" Write-Output " +====================================================================+" Write-Output "" Write-Host " CHANGING THE OWNER AND PERMISSIONS COULD BREAK THINGS," -ForegroundColor Red Write-Host " SO PROCEED WITH CAUTION AND DO IT AT YOUR OWN RISK !!" -ForegroundColor Red Write-Output "" Write-Output " CURRENT SCRIPT CONFIG:" Write-Output " ----------------------" Write-Output " -SetAclFilePath: $SetAclFilePath" Write-Output " -UserName......: $UserName" Write-Output " -RegKeys.......:" Write-Output ($RegKeys | ForEach-Object {" $_"}) Write-Output "" } function Confirm-Continue { Write-Host " Press 'Y' key to continue or 'N' to exit." Write-Host "" Write-Host " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} else {Clear-Host} } function Get-RegistryOwnership { param( [string]$setAclFilePath = "$env:ProgramFiles\SetACL\setacl.exe", [string[]]$regKeys, [string]$userName = "$env:UserName" ) try { if (-not (Test-Path $setAclFilePath)) { $ex = New-Object System.IO.FileNotFoundException("SetACL.exe file not found at path '$setAclFilePath'.", $setAclFilePath) throw $ex } $logFile = New-TemporaryFile foreach ($key in $regKeys) { 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 #$logContent = Get-Content -Path $logFile.FullName Write-Output "" #Write-Output $logContent } } catch { Write-Host "Something went wrong when calling '$($MyInvocation.MyCommand.Name)' method:" Write-Host "" Write-Warning ($_.Exception) Write-Host "" Write-Error -Message ($_.Exception | Format-List * -Force | Out-String) Write-Host "" Write-Host "Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } } function Show-GoodbyeScreen { Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" Write-Host "Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Get Full Registry Ownership Tool - by Elektro" [CultureInfo]::CurrentUICulture = "en-US" $SetAclFilePath = "$env:ProgramFiles\SetACL\SetACL.exe" $RegKeys = "HKEY_CLASSES_ROOT", "HKEY_CURRENT_USER", "HKEY_LOCAL_MACHINE", "HKEY_USERS", "HKEY_CURRENT_CONFIG" $UserName = $env:UserName try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Confirm-Continue Get-RegistryOwnership -SetAclFilePath $SetAclFilePath -RegKeys $RegKeys -UserName $UserName Show-GoodbyeScreen
|
|
|
|
|
35
|
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. 
# --------------------------------------------- # # Automated AppX Package Installer - by Elektro # # --------------------------------------------- # # This script will find any AppX package files within the current directory (without recursion), # print info about the package, print a message in case of the package is already installed, # and install the package in case of it is not installed, handling errors during installation. # --------------------------------------------------------------------- # Takes a string argument that points to an AppX package name or file, # then it uses a regular expression to match the package string pattern # and returns a custom object with the Name, Version, Architecture, # PublisherId and other properties. # # Parameters: # -PackageString: A string that points to the file name # or full path of an AppX package file. # # Returns: # A PSCustomObject object with these properties defined: # [String] Name # [String] Version # [String] Architecture # [String] PublisherId # [String] FullName function Get-AppXPackageInfo { param ( [Parameter(Mandatory=$true)] [string]$PackageString ) #$dirname = [System.IO.Path]::GetDirectoryName($PackageString) #if ([string]::IsNullOrEmpty($dirname)) { # $dirname = $PWD #} $filename = [System.IO.Path]::GetFileName($PackageString) -replace "(?i)\.appxbundle$", "" -replace "(?i)\.msixbundle$", "" -replace "(?i)\.appx$", "" $regex = '^(?<Name>.+?)_(?<Version>.+?)_(?<Architecture>.+?)_(?<chars>~)?_(?<PublisherId>.+)$' $match = $filename -match $regex if (!$match) { throw "Unable to parse the string package: '$PackageString'" } [string]$packageName = $matches['Name'] [string]$packageVersion = $matches['Version'] [string]$packageArchitecture = $matches['Architecture'] [string]$packagePublisherId = $matches['PublisherId'] [string]$chars = $matches['chars'] [string]$packageFullName = "${packageName}_${packageVersion}_${packageArchitecture}_${chars}_${packagePublisherId}" #[string]$packageFullPath = [System.IO.Path]::Combine($dirname, "$filename.Appx") [PSCustomObject]@{ Name = $packageName Version = $packageVersion Architecture = $packageArchitecture PublisherId = $packagePublisherId FullName = $packageFullName #FullPath = $packageFullPath } } # Determines whether an Appx package matching the specified # name, version and architecture is installed in the system. # # Parameters: # -Name........: The package name. # -Version.....: The package version. # -Architecture: The package architecture ("x86", "x64"). # # Returns: # $true if the AppX package is installed in the system, # $false otherwise. function IsAppxPackageInstalled() { param ( [Parameter(Mandatory=$true)] [string]$name, [Parameter(Mandatory=$true)] [string]$version, [Parameter(Mandatory=$true)] [string]$architecture ) if ($architecture -eq "neutral") { $architecture = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture } $packages = Get-AppxPackage "$($name)*" -ErrorAction Stop | Where-Object { $_.Name.ToLower() -eq $name.ToLower() -and $_.Version.ToLower() -eq $version.ToLower() -and "$($_.Architecture)".ToLower() -eq $architecture.ToLower() } return ($packages.Count -gt 0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Automated AppX Package Installer - by Elektro" [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } # Hides the progress-bar for 'Add-AppxPackage' cmdlet in this script. # Thanks to @Santiago Squarzon for the tip: https://stackoverflow.com/questions/75716867 # https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.3#progresspreference $ProgressPreference = "Ignore" Do { Clear-Host Write-Output "" Write-Output " $($host.ui.RawUI.WindowTitle)" Write-Output " +=====================================================+" Write-Output " | |" Write-Output " | This script will find any AppX package files |" Write-Output " | within the current directory (without recursion), |" Write-Output " | print info about the package, print a message |" Write-Output " | in case of the package is already installed, |" Write-Output " | and install the package in case of it is |" Write-Output " | not installed, handling errors during installation. |" Write-Output " | |" Write-Output " +=====================================================+" Write-Output "" Write-Host " -Continue? (Y/N)" $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} else {Clear-Host} $appxFiles = Get-ChildItem -Path "$PWD" -Filter "*.appx*" if ($appxFiles.Count -eq 0) { Write-Warning "No Appx files were found in the current directory." Write-Host "" $LastExitCode = 2 } else { $appxFiles | ForEach-Object { # The AppX package string. It can be a file name (with or without extension), or a full path. $packageString = $_.FullName $packageInfo = Get-AppXPackageInfo -PackageString $packageString $nameVerArch = "$($packageInfo.Name) v$($packageInfo.Version) ($($packageInfo.Architecture))" Write-Host "Package Info.:" -ForegroundColor Gray Write-Host ($packageInfo | Format-List | Out-String).Trim() -ForegroundColor DarkGray Write-Host "" $isInstalled = IsAppxPackageInstalled -Name $packageInfo.Name -Version $packageInfo.Version -Architecture $packageInfo.Architecture if ($isInstalled) { Write-Warning "Package $nameVerArch is already installed." Write-Warning "Installation is not needed." } else { Write-Host "Package $nameVerArch is ready to install." Write-Host "Installing package..." try { Add-AppxPackage -Path "$($_.FullName)" -ErrorAction Stop Write-Host "Package $nameVerArch has been successfully installed." -BackgroundColor Black -ForegroundColor Green } catch { Write-Host "Error installing package $nameVerArch" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Error -Message ($_.Exception | Format-List * -Force | Out-String) $LastExitCode = 1 Break } } Write-Host "" $LastExitCode = 0 } } Write-Host "Program will terminate now with exit code $LastExitCode. Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Exit($LastExitCode)
|
|
|
|
|
36
|
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 #Requires -Version 3 # https://gist.github.com/heaths/77fbe0b44496960fab25c2eb0b9e8475 [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Position = 0, ValueFromPipeline = $true)] [ValidateNotNullOrEmpty()] [string[]] $ProductCode ) [System.Console]::Title = "Remove Windows Installer product registration for missing MSI packages" [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } $ErrorActionPreference = 'Stop' [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 $loc = data { ConvertFrom-StringData @' Error_Elevation_Required = You must run this script in an elevated command prompt Error_64Bit_Required = You must run this in a 64-bit command prompt Error_PackageManagement_Required = Please install PackageManagement from http://go.microsoft.com/fwlink/?LinkID=746217 Process_Remove_Args1 = Remove registration for {0} Verbose_Install_MSI = Installing the "MSI" module Verbose_Scan_Missing = Scanning for products missing cached packages Verbose_Remove_Key_Args1 = Removing key : {0} Verbose_Remove_Value_Args2 = Removing value: {0}\\{1} Verbose_Remove_Source_Reg = Removing source registration Verbose_Remove_Product_Reg = Removing product registration Verbose_Remove_Upgrade_Reg = Removing upgrade registration Verbose_Remove_Component_Reg = Removing component registration Verbose_Found_Source_Args2 = Cache missing for {0} but found source at {1} '@ } $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent() $principal = New-Object System.Security.Principal.WindowsPrincipal $identity if (!$principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) { throw $loc.Error_Elevation_Required } if ([System.Environment]::Is64BitOperatingSystem) { if (![System.Environment]::Is64BitProcess) { throw $loc.Error_64Bit_Required } } $pack = { param ( [string] $Guid ) if (!$Guid) { return } $Guid = (New-Object System.Guid $Guid).ToString("N").ToUpperInvariant() $sb = New-Object System.Text.StringBuilder $translation.Count foreach ($i in $translation) { $null = $sb.Append($Guid[$i]) } $sb.ToString() } $test = { param ( $Product ) if ($Product.PSPath -and ($Product | Test-Path)) { return $true } if ($Product.PackageName) { $Product | Get-MSISource | ForEach-Object { $path = Join-Path $_.Path $Product.PackageName if ($path | Test-Path) { Write-Host ($loc.Verbose_Found_Source_Args2 -f $Product.ProductCode, $path) return $true } } } $false } $remove = { param ( [string] $Key ) if (Test-Path $Key) { Write-Host ($loc.Verbose_Remove_Key_Args1 -f $Key) Remove-Item -Recurse -Force $Key } } $removeChild = { param ( [string] $Key, [string] $Name ) if (Test-Path $Key) { Get-ChildItem $Key | ForEach-Object { $obj = $_ | Get-ItemProperty if ($obj.$Name -ne $null) { Write-Host ($loc.Verbose_Remove_Value_Args2 -f $_.Name, $Name) Remove-ItemProperty -Force -Name $Name -LiteralPath $_.PSPath $obj = Get-ItemProperty -LiteralPath $_.PSPath if (!$obj) { Write-Host ($loc.Verbose_Remove_Key_Args1 -f $_.Name) Remove-Item -Recurse -Force -LiteralPath $_.PSPath } } } } } if (!$ProductCode) { # Install the MSI module if missing. if (!(Get-Module -ListAvailable MSI)) { Write-Host $loc.Verbose_Install_MSI # Make sure PackageManagement is installed (comes with WMF 5.0 / Windows 10). if (!(Get-Module -ListAvailable PackageManagement)) { throw $loc.Error_PackageManagement_Required } Install-Module MSI -Scope CurrentUser -SkipPublisherCheck -Force } Write-Host $loc.Verbose_Scan_Missing foreach ($msi in (Get-MSIProductInfo -UserContext Machine)) { if (!(&$test $msi)) { $ProductCode += $msi.ProductCode } } } foreach ($code in $ProductCode) { if ($PSCmdlet.ShouldProcess($msi, $loc.Process_Remove_Args1 -f $code)) { $packedProductCode = &$pack $code Write-Host $loc.Verbose_Remove_Source_Reg &$remove "Registry::HKCL\SOFTWARE\Classes\Installer\Products\$packedProductCode" &$remove "Registry::HKCL\SOFTWARE\Classes\Installer\Features\$packedProductCode" &$remove "Registry::HKLM\SOFTWARE\Classes\Installer\Products\$packedProductCode" &$remove "Registry::HKLM\SOFTWARE\Classes\Installer\Features\$packedProductCode" Write-Host $loc.Verbose_Remove_Product_Reg &$remove "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\$packedProductCode" &$remove "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$code" &$remove "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\$packedProductCode" &$remove "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$code" &$remove "Registry::HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\$code" Write-Host $loc.Verbose_Remove_Upgrade_Reg &$removeChild "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UpgradeCodes" $packedProductCode &$removeChild "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UpgradeCodes" $packedProductCode Write-Host $loc.Verbose_Remove_Component_Reg &$removeChild "Registry::HKCL\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components" $packedProductCode &$removeChild "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components" $packedProductCode } } Write-Host "Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") Exit(0) <# .SYNOPSIS Removes Windows Installer product registrtation for missing or specified MSIs .DESCRIPTION If Windows Installer product registration is corrupt (exit code 1610) or package sources are missing (exit code 1603, error message 1714; or exit code 1612), you can use this script in an elevated PowerShell command shell to clean up the registration is a transactional manner to avoid making machine state worse. Please note that this should be a last resort and only for those issues above. The old msizap.exe program was frought with issues and can make matters worse if not used properly. .PARAMETER ProductCode Optional list of ProductCode to clean up; otherwise, ProductCodes are scanned from products with missing sources. .EXAMPLE PS> Unregister-MissingMSIs.ps1 Removes per-machine product registration for products with missing cached MSIs. .EXAMPLE PS> Unregister-MissingMSIs.ps1 '{7B88D6BB-A664-4E5A-AB81-C435C8639A4D}' Remove per-machine product registration for the specified ProductCode only. #>
|
|
|
|
|
37
|
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. 
@Echo OFF & CHCP 1252 >NUL & Title FFMPEG Convert Video to MP4 - Sony Vegas Compatible - Tool by Elektro ECHO: This script will convert the source video file ECHO: to a MP4 video compatible with Sony Vegas. ECHO: YOU MUST DROP A MKV FILE TO THIS BATCH-FILE. ) ECHO: Output file: " %~dpn1_VEGAS.mp4" CHOICE /C YN /M "Continue?" CLS ) ) ::::::::::::::::::::::::::::::::::::::::::::::::::::::: REM How to encode Vegas-compatible H.264 file using FFmpeg: REM http://www.konstantindmitriev.ru/blog/2014/03/02/how-to-encode-vegas-compatible-h-264-file-using-ffmpeg/ ECHO+Choose a encoding preset: ECHO+ [6] medium – default preset CHOICE /C "0123456789" /M "" IF %ERRORLEVEL% EQU 2 (SET "preset=ultrafast" ) IF %ERRORLEVEL% EQU 3 (SET "preset=superfast" ) IF %ERRORLEVEL% EQU 4 (SET "preset=veryfast" ) IF %ERRORLEVEL% EQU 5 (SET "preset=faster" ) IF %ERRORLEVEL% EQU 6 (SET "preset=fast" ) IF %ERRORLEVEL% EQU 7 (SET "preset=medium" ) IF %ERRORLEVEL% EQU 8 (SET "preset=slow" ) IF %ERRORLEVEL% EQU 9 (SET "preset=slower" ) IF %ERRORLEVEL% EQU 10 (SET "preset=veryslow" ) :: SET "forcedFPS=-r 23.976" CLS "%~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" CLS Color A Echo: Video conversion completed successfully. | MORE | MORE Echo: Input.: " %~1" | MORE Echo: Output: " %~dpn1_VEGAS.mp4" | MORE Color C Echo: Video conversion completed with errors. | MORE | MORE Echo: Input.: " %~1" | MORE Echo: Output: " %~dpn1_VEGAS.mp4" | MORE )
|
|
|
|
|
38
|
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. 
<# =========================================================================================== | | | Variables | | | =========================================================================================== #> $inputDirectoryPath = "$PSScriptRoot" $fileNameSearchPattern = "*.*" $imageExts = @("avif", "bmp", "jp2", "jpg", "png", "tga", "tif", "webp") $recurse = $false $irfanviewFullPath = "C:\Program Files\IrfanView\i_view64.exe" # Cropping values $x = 12 $y = 20 $width = 620 $height = 560 # For cropping images that are jpg/jpeg $jpgQuality = 95 <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +=========================================+" Write-Host " | |" Write-Host " | This script will search for image files |" Write-Host " | in the current working directory, and |" Write-Host " | use IrfanView to crop them using the |" Write-Host " | specified cropping settings. |" Write-Host " | |" Write-Host " +=========================================+" Write-Host "" Write-Host " Script Settings " -ForegroundColor DarkGray Write-Host " ========================" -ForegroundColor DarkGray Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray Write-Host " Search File Extensions..: $($imageExts -join ', ')" -ForegroundColor DarkGray Write-Host " IrfanView Full Path.....: $irfanviewFullPath" -ForegroundColor DarkGray Write-Host " JPG Quality.............: $jpgQuality%" -ForegroundColor DarkGray Write-Host " Cropping.values.........: X=$x, Y=$y, Width=$width, Height=$height" -ForegroundColor DarkGray Write-Host "" } function Confirm-Continue { Write-Host " Press 'Y' key to continue or 'N' to exit." Write-Host "" Write-Host " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} } function Validate-Parameters { if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) { Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if (-not (Test-Path -LiteralPath $irfanviewFullPath -PathType Leaf)) { Write-Host " Irfanview file path does not exists!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ($imageExts.Count -eq 0) { Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } } function Crop-Files { Clear-Host $imageFiles = $null if ($recurse) { $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') } } else { $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') } } foreach ($imageFile in $imageFiles) { Write-Host " Cropping file: $($imageFile.FullName.Replace($inputDirectoryPath, "."))" $exitCode = $null try { $process = New-Object System.Diagnostics.Process $process.StartInfo.FileName = $irfanviewFullPath $process.StartInfo.Arguments = "`"$($imageFile.FullName)`" /crop=($x,$y,$width,$height) /jpgq=$jpgQuality /convert=""$($imageFile.FullName)""" $process.StartInfo.UseShellExecute = $false $started = $process.Start() | Out-Null $exited = $process.WaitForExit() $exitCode = $process.ExitCode } catch { Write-Host "" Write-Host " Error running IrfanView process." -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Error -Message ($_.Exception.Message) Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ($exitCode -eq 0) { Write-Host " File cropped successfully." -ForegroundColor DarkGreen Write-Host "" } else { Write-Host " Error cropping file. IrfanView Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to ignore and continue..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") } } } function Show-GoodbyeScreen { Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Crop image files - by Elektro" #[System.Console]::SetWindowSize(146, 27) [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Validate-Parameters Confirm-Continue Crop-Files Show-GoodbyeScreen
|
|
|
|
|
39
|
Programación / Scripting / [APORTE] [PowerShell] IrfanView | Convert image files to JPG
|
en: 4 Marzo 2024, 14:45 pm
|
El siguiente script desarrollado en PowerShell y dependiente del programa de terceros IrfanView, sirve para convertir todos los archivos de imagen del directorio actual, a formato JPG. En la sección "Variables" dentro del script pueden personalizar la calidad de codificación JPG y los tipos de archivos de imagen a procesar entre otras cosas configurables. 
<# =========================================================================================== | | | Variables | | | =========================================================================================== #> $inputDirectoryPath = "$PSScriptRoot" $fileNameSearchPattern = "*.*" $imageExts = @("avif", "bmp", "jp2", "jpg", "png", "tga", "tif", "webp") $recurse = $false $irfanviewFullPath = "C:\Program Files\IrfanView\i_view64.exe" $jpgQuality = 95 $overwriteConfirm = $true $sendToRecycleBinConvertedFiles = $true <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +===========================================+" Write-Host " | |" Write-Host " | This script will search for image files |" Write-Host " | in the current working directory, and use |" Write-Host " | IrfanView to convert them to JPG format. |" Write-Host " | |" Write-Host " +===========================================+" Write-Host "" Write-Host " Script Settings " -ForegroundColor DarkGray Write-Host " ========================" -ForegroundColor DarkGray Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray Write-Host " Search File Extensions..: $($imageExts -join ', ')" -ForegroundColor DarkGray Write-Host " IrfanView Full Path.....: $irfanviewFullPath" -ForegroundColor DarkGray Write-Host " JPG Quality.............: $jpgQuality%" -ForegroundColor DarkGray Write-Host " Confirm Overwrite JPG...: $overwriteConfirm" -ForegroundColor DarkGray Write-Host " Recycle Converted Files.: $sendToRecycleBinConvertedFiles" -ForegroundColor DarkGray Write-Host "" } function Confirm-Continue { Write-Host " Press 'Y' key to continue or 'N' to exit." Write-Host "" Write-Host " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} } function Validate-Parameters { if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) { Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if (-not (Test-Path -LiteralPath $irfanviewFullPath -PathType Leaf)) { Write-Host " Irfanview file path does not exists!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ($imageExts.Count -eq 0) { Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } } function Convert-Files { Clear-Host Add-Type -AssemblyName Microsoft.VisualBasic $imageFiles = $null if ($recurse) { $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') } } else { $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $imageExts -contains $_.Extension.ToLower().TrimStart('.') } } foreach ($imageFile in $imageFiles) { Write-Host " Converting to JPG: $($imageFile.FullName.Replace($inputDirectoryPath, "."))" $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($imageFile.Name) $outputFilePath = Join-Path -Path ($imageFile.Directory.FullName) -ChildPath "$fileNameWithoutExtension.jpg" if ((Test-Path -LiteralPath $outputFilePath -PathType Leaf) -and ($overwriteConfirm)) { # El archivo no existe o no se debe sobrescribir Write-Warning " Output JPG file already exists but `$overwriteConfirm variable is disabled." Write-Warning " The output JPG file will be overwitten if you continue." Write-Host "" Confirm-Continue Write-Host "" } $exitCode = $null try { $procStartInfo = New-Object System.Diagnostics.ProcessStartInfo $procStartInfo.FileName = $irfanviewFullPath $procStartInfo.Arguments = "`"$($imageFile.FullName)`" /jpgq=$jpgQuality /convert=`"$outputFilePath`"" $procStartInfo.UseShellExecute = $false $process = New-Object System.Diagnostics.Process $process.StartInfo = $procStartInfo $process.Start() | Out-Null $process.WaitForExit() $exitCode = $process.ExitCode } catch { Write-Host "" Write-Host " Error running IrfanView process." -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Error -Message ($_.Exception.Message) Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ($exitCode -eq 0) { Write-Host " File converted successfully." -ForegroundColor DarkGreen if ($sendToRecycleBinConvertedFiles) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($imageFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') Write-Host " File sent to recycle bin." -ForegroundColor DarkGray } Write-Host "" } else { Write-Host " Error converting file to JPG. IrfanView Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red Write-Host "" } } } function Show-GoodbyeScreen { Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Convert image files to JPG - by Elektro" #[System.Console]::SetWindowSize(146, 27) [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Validate-Parameters Confirm-Continue Convert-Files Show-GoodbyeScreen
|
|
|
|
|
40
|
Programación / Scripting / [APORTE] [PowerShell] ImageMagick | Convert image files to ICO
|
en: 4 Marzo 2024, 14:41 pm
|
El siguiente script desarrollado en PowerShell y dependiente del programa de terceros ImageMagick, sirve para convertir todos los archivos de imagen del directorio actual, a formato ICO. Soportando transparencia. En la sección "Variables" dentro del script pueden personalizar los tamaños de las capas del icono, la calidad, y el color usado como transparencia entre otras cosas configurables. 
<# =========================================================================================== | | | Variables | | | =========================================================================================== #> $inputDirectoryPath = "$PSScriptRoot" $recurse = $true $fileSearchExts = @("avif", "bmp", "jp2", "jpg", "jpeg", "png", "tga", "tif", "webp") $fileNameSearchPattern = "*.*" #$fileNameSearchPattern = "Cover.*" $iconSizes = @(256, 128, 96, 64, 48, 32, 24, 16) $iconBackColor = "transparent" $iconQuality = 100 $imageMagickFullPath = "$PSScriptRoot\magick.exe" $imageMagickArgs = @("-define icon:auto-resize=`"$($iconSizes -join ',')`"", "-background $iconBackColor", "-gravity center", "-extent 1:1#", "-quality $iconQuality" ) $overwriteConfirm = $true $sendToRecycleBinConvertedFiles = $false <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +=============================================+" Write-Host " | |" Write-Host " | This script will search for image files |" Write-Host " | in the current working directory, and use |" Write-Host " | ImageMagick to convert them to ICO format. |" Write-Host " | |" Write-Host " +============================================+" Write-Host "" Write-Host " Script Settings " -ForegroundColor DarkGray Write-Host " ========================" -ForegroundColor DarkGray Write-Host " Input Directory Path....: $inputDirectoryPath" -ForegroundColor DarkGray Write-Host " Recursive File Search...: $recurse" -ForegroundColor DarkGray Write-Host " Search File Name Pattern: $fileNameSearchPattern" -ForegroundColor DarkGray Write-Host " Search File Extensions..: $($fileSearchExts -join ', ')" -ForegroundColor DarkGray Write-Host " ImageMagick Full Path...: $imageMagickFullPath" -ForegroundColor DarkGray Write-Host " Icon Sizes (and order)..: $($iconSizes -join ', ')" -ForegroundColor DarkGray Write-Host " Icon Background Color...: $iconBackColor" -ForegroundColor DarkGray Write-Host " Icon Quality............: $iconQuality" -ForegroundColor DarkGray Write-Host " Confirm Overwrite ICO...: $overwriteConfirm" -ForegroundColor DarkGray Write-Host " Recycle Converted Files.: $sendToRecycleBinConvertedFiles" -ForegroundColor DarkGray # Write-Host " ImageMagick Arguments...: $($imageMagickArgs -join $([Environment]::NewLine) + ' ')" -ForegroundColor DarkGray Write-Host "" } function Confirm-Continue { Write-Host " Press 'Y' key to continue or 'N' to exit." Write-Host "" Write-Host " -Continue? (Y/N)" do { $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") $char = $key.Character.ToString().ToUpper() if ($char -ne "Y" -and $char -ne "N") { [console]::beep(1500, 500) } } while ($char -ne "Y" -and $char -ne "N") if ($char -eq "N") {Exit(1)} } function Validate-Parameters { if (-not (Test-Path -LiteralPath $inputDirectoryPath -PathType Container)) { Write-Host " Input directory path does not exists!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if (-not (Test-Path -LiteralPath $imageMagickFullPath -PathType Leaf)) { Write-Host " ImageMagick file path does not exists!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ([string]::IsNullOrEmpty($fileNameSearchPattern)) { Write-Host " `$fileNameSearchPattern variable is null!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ($fileSearchExts.Count -eq 0) { Write-Host " No image file extensions were specified!" -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } } function Convert-Files { Clear-Host Add-Type -AssemblyName Microsoft.VisualBasic $imageFiles = $null if ($recurse) { $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern -Recurse | Where-Object { $fileSearchExts -contains $_.Extension.ToLower().TrimStart('.') } } else { $imageFiles = Get-ChildItem -LiteralPath $inputDirectoryPath -Filter $fileNameSearchPattern | Where-Object { $fileSearchExts -contains $_.Extension.ToLower().TrimStart('.') } } foreach ($imageFile in $imageFiles) { Write-Host " Converting to ICO: $($imageFile.FullName.Replace($inputDirectoryPath, "."))" $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($imageFile.Name) $outputFilePath = Join-Path -Path ($imageFile.Directory.FullName) -ChildPath "$fileNameWithoutExtension.ico" if ((Test-Path -LiteralPath $outputFilePath -PathType Leaf) -and ($overwriteConfirm)) { # El archivo no existe o no se debe sobrescribir Write-Warning " Output ICO file already exists but `$overwriteConfirm variable is disabled." Write-Warning " The output ICO file will be overwitten if you continue." Write-Host "" Confirm-Continue Write-Host "" } $exitCode = $null try { $procStartInfo = New-Object System.Diagnostics.ProcessStartInfo $procStartInfo.FileName = $imageMagickFullPath $procStartInfo.Arguments = "`"$($imageFile.FullName)`" $($imageMagickArgs -join ' ') `"$outputFilePath`"" $procStartInfo.UseShellExecute = $false $process = New-Object System.Diagnostics.Process $process.StartInfo = $procStartInfo $process.Start() | Out-Null $process.WaitForExit() $exitCode = $process.ExitCode } catch { Write-Host "" Write-Host " Error running ImageMagick process." -BackgroundColor Black -ForegroundColor Red Write-Host "" Write-Error -Message ($_.Exception.Message) Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(1) } if ($exitCode -eq 0) { Write-Host " File converted successfully." -ForegroundColor DarkGreen if ($sendToRecycleBinConvertedFiles) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($imageFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') Write-Host " File sent to recycle bin." -ForegroundColor DarkGray } Write-Host "" } else { Write-Host " Error converting file to ICO. ImageMagick Exit Code: $exitCode" -BackgroundColor Black -ForegroundColor Red Write-Host "" } } } function Show-GoodbyeScreen { Write-Host " Operation Completed!" -BackgroundColor Black -ForegroundColor Green Write-Host "" Write-Host " Press any key to exit..." $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Exit(0) } <# =========================================================================================== | | | Main | | | =========================================================================================== #> [System.Console]::Title = "Convert image files to ICO - by Elektro" #[System.Console]::SetWindowSize(146, 27) [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Validate-Parameters Confirm-Continue Convert-Files Show-GoodbyeScreen
|
|
|
|
|
|
| |
|