|
122
|
Programación / Scripting / [APORTE] [PowerShell] RAR.exe | Multi-Compression Test Tool (Para Archivos)
|
en: 2 Marzo 2024, 13:01 pm
|
El siguiente script desarrollado en PowerShell y dependiente del programa externo RAR.exe (WinRAR), sirve para comprimir cada archivo dentro del directorio actual de forma individual, con compresión máxima, y utilizando los tamaños de diccionario especificados. La sección "Variables" dentro del script permite configurar varias cosas, entre ellas: - Los tamaños de diccionario. - Las extensiones de archivo que se deben procesar sin aplicar compresión. - Preservar solamente el archivo RAR generado con el menor tamaño de todos. (eliminar los archivos RAR de mayor tamaño) - Especificar una diferencia de tamaño (tolerancia) arbitraria para eliminar archivos RAR generados (con mayores tamaños de diccionario) de un tamaño de archivo similar. - Enviar los archivos RAR eliminados a la papelera de reciclaje. Es muy útil, por ejemplo, para comprimir de forma automatizada archivos ISO de consolas, y obtener así el mejor resultado entre Tamaño de diccionario / Tamaño de archivo.
<# =========================================================================================== | | | Variables | | | =========================================================================================== #> $rarExecutablePath = "C:\Program Files\WinRAR\rar.exe" $dictionarySizes = @(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048) $toleranceSizeDiff = "1MB" $keepOnlySmallestRarFile = $true $sendRarFilesToRecycleBin = $false $compressedFileTypesArchive = @( "7z" , "arc", "bz2" , "bzip", "bzip2", "gz" , "gz2", "gza" , "gzi" , "gzip" , "lha", "lz" , "lz4" , "lzh" , "lzma" , "rar", "sfx", "tgz" , "tlz" , "tlzma", "uha", "zip", "zipx", "zpaq" ) $compressedFileTypesAudio = @( "aac", "ac3", "fla","flac", "m4a", "mp3", "ogg", "ogm", "usm", "wma" ) $compressedFileTypesVideo = @( "asf", "avc", "avi" , "bik" , "bk2" , "f4v" , "flv" , "m1v", "m2t", "m2ts", "m2v" , "m4v" , "mpv4", "mkv", "mov", "mp4" , "mpeg", "mpg" , "mts" , "qt" , "ts" , "vob" , "vp6" , "webm", "wmv" ) $compressedFileTypesOther = @( "avif", "jpeg", "jpg" , "gif" , "pdf", "pam" , "paq6", "paq7", "paq8", "par" , "par2", "wad" ) [string]$fileTypesToKeepUncompressed = ( $compressedFileTypesArchive + $compressedFileTypesAudio + $compressedFileTypesVideo + $compressedFileTypesOther ) -join ';' <# =========================================================================================== | | | rar.exe commands (only those used in this script) | | | =========================================================================================== <Commands> a Add files to archive <Switches> -am[s,r] Archive name and time [save, restore] -c- Disable comments show -cfg- Ignore configuration file and RAR environment variable. -dh Open shared files -ep1 Exclude base directory from names -ht[b|c] Select hash type [BLAKE2,CRC32] for file checksum -id[c,d,n,p,q] Display or disable messages -ilog[name] Log errors to file -isnd[-] Control notification sounds -m<0..5> Set compression level (0-store...3-default...5-maximal) -ma[4|5] Specify a version of archiving format -md<n>[k,m,g] Dictionary size in KB, MB or GB -ms[list] Specify file types to store. -o[+|-] Set the overwrite mode -oc Set NTFS Compressed attribute. -oh Save hard links as the link instead of the file -oi[0-4][:min] Save identical files as references -ol[a] Process symbolic links as the link [absolute paths] -oni Allow potentially incompatible names -qo[-|+] Add quick open information [none|force] -r Recurse subdirectories -ri<P>[:<S>] Set priority (0-default,1-min..15-max) and sleep time in ms -s- Disable solid archiving -t Test files after archiving -tk Keep original archive time -tl Set archive time to newest file -ts[m,c,a,p] Save or restore time (modification, creation, access, preserve) -u Update files -w<path> Assign work directory #> <# =========================================================================================== | | | .NET Code | | | =========================================================================================== #> Add-Type -TypeDefinition @" using System; using System.Runtime.InteropServices; public class Win32Functions { [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)] public static extern long StrFormatByteSizeW(long fileSize, System.Text.StringBuilder buffer, int bufferSize); } "@ <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +========================================================+" Write-Host " | |" Write-Host " | This script will use RAR.exe to compress each file in |" Write-Host " | the current working directory individually, each using |" Write-Host " | different dictionary sizes, with max. compression, |" Write-Host " | generating this way multiple RAR files for evaluating |" Write-Host " | compression rates on these dictionary sizes. |" Write-Host " | |" Write-Host " +=========================================================+" Write-Host "" Write-Host " Script Settings " -ForegroundColor DarkGray Write-Host " ===========================" -ForegroundColor DarkGray Write-Host " RAR Executable Path: $([System.IO.Path]::GetFullPath($rarExecutablePath))" -ForegroundColor Gray Write-Host "" -ForegroundColor DarkGray Write-Host " Dictionary Sizes (Megabyte): $($dictionarySizes -join ', ')" -ForegroundColor Gray Write-Host " The script will create a RAR archive for each specified dictionary size." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " File Types To Keep Uncompressed: `$keepCompressedFileTypesUncompressed" -ForegroundColor Gray Write-Host " The script will instruct RAR to don't compress the specified known compressed file types." -ForegroundColor DarkGray Write-Host " (See `$keepCompressedFileTypesUncompressed variable definition to manage the file types)" -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Tolerance File Size Difference: $toleranceSizeDiff" -ForegroundColor Gray Write-Host " Any newly created RAR file whose file size compared to previously " -ForegroundColor DarkGray Write-Host " created RAR files is within the specified tolerance value, it will be deleted." -ForegroundColor DarkGray Write-Host " For example, if `$toleranceSizeDiff value is 1MB:" -ForegroundColor DarkGray Write-Host " If a created RAR file of 32 MB dict. size has a file size of 100 MB," -ForegroundColor DarkGray Write-Host " and then a newly created RAR file of 64 MB dict. size has a file size of 99 MB, " -ForegroundColor DarkGray Write-Host " the RAR file of 64 MB dict. size will be deleted because it only differs in 1MB or less." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Keep only smallest rar file: $keepOnlySmallestRarFile" -ForegroundColor Gray Write-Host " If True, the script will delete any newly created RAR file " -ForegroundColor DarkGray Write-Host " whose file size is bigger than previously created RAR files." -ForegroundColor DarkGray Write-Host " Note: it takes into account the specified `$toleranceSizeDiff value." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Send RAR files to recycle bin: $sendRarFilesToRecycleBin" -ForegroundColor Gray Write-Host " If True, the script will send RAR files to recycle bin instead of permanently deleting them." -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)} else {Clear-Host} } function Compress-Files { Add-Type -AssemblyName Microsoft.VisualBasic $dictionarySizes = $dictionarySizes | Sort-Object # Partir y formatear la cadena de file types para acomodarlo a la linea de argumentos de rar.exe if (-not [String]::IsNullOrEmpty($fileTypesToKeepUncompressed)) { $fileTypeTokens = $fileTypesToKeepUncompressed -split ';' $fileTypesArgumentLines = @() for ($i = 0; $i -lt $fileTypeTokens.Count; $i += 20) { $fileTypesArgumentLines += "-ms" + ($fileTypeTokens[$i..($i + 19)] -join ';') + [Environment]::NewLine } if ($fileTypesArgumentLines.Count -gt 0) { $fileTypesArgumentLines[-1] = $fileTypesArgumentLines[-1] -replace [Environment]::NewLine, '' } } else { $fileTypesArgumentLines = "-ms " } foreach ($inputFile in Get-ChildItem -LiteralPath "$PSScriptRoot" -File) { if ($inputFile.Name -eq [System.IO.Path]::GetFileName($PSCommandPath)) { continue } # Keeps track of created rar files by rar.exe $createdRarFiles = New-Object System.Collections.Generic.List[System.IO.FileInfo] foreach ($size in $dictionarySizes) { if (($size -ne $dictionarySizes[0]) -and ($inputFile.Length * 4) -le ($size * 1MB)) { $formattedSize = Format-FileSize -fileSize $inputFile.Length Write-Host "Ignoring compression with too big dictionary size of $size mb for a $formattedSize file: `"$($inputFile.Name)`"..." -ForegroundColor Yellow continue } $outputRarFilePath = "$($inputFile.FullName)_$($size)mb.rar" $errorLogFilePath = "$($inputFile.FullName)_$($size)mb_error.log" $arguments = @( " a -u -ams -c- -cfg- -dh -ep1 -htb -idcdn -isnd- -iver -m5 -ma5 -md$($size)m", " -o+ -oc -oh -oi2 -ol -oni -qo+ -r -ri0:0 -s- -t -tk -tl -tsmca+", " $fileTypesArgumentLines", " -x`"*\$($MyInvocation.MyCommand.Name)`"", " -w`"$($env:TEMP)`"", " -ilog`"$errorLogFilePath`"", " -- `"$outputRarFilePath`"", " -- `"$($inputFile.FullName)`"" ) Write-Host "Compressing file with $size mb dictionary dize: `"$($inputFile.Name)`"..." #Write-Host "" #Write-Host "rar.exe arguments:" -ForegroundColor DarkGray #Write-Host ($arguments -join [Environment]::NewLine) -ForegroundColor DarkGray $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $rarExecutablePath $psi.Arguments = $arguments -join ' ' $psi.RedirectStandardOutput = $false $psi.UseShellExecute = $false $psi.CreateNoWindow = $false $process = [System.Diagnostics.Process]::Start($psi) $process.WaitForExit() $outputRarFile = New-Object System.IO.FileInfo($outputRarFilePath) $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length Write-Host "" Write-Host "Created rar with file name: $($outputRarFile.Name) ($formattedOutputRarFileSize)" -ForegroundColor DarkGreen if ($toleranceSizeDiff -ne $null) { if ($createdRarFiles.Count -ne 0) { $outputRarFileMB = [Math]::Floor($outputRarFile.Length / $toleranceSizeDiff) $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length foreach ($rarFile in $createdRarFiles) { if ($rarFile.Exists) { $sizeMB = [Math]::Floor($rarFile.Length / $toleranceSizeDiff) $formattedRarFileSize = Format-FileSize -fileSize $rarFile.Length if ($outputRarFileMB -eq $sizeMB) { Write-Host "" Write-Host "File size of this created RAR file ($formattedOutputRarFileSize) is within the $toleranceSizeDiff tolerance difference" -ForegroundColor DarkGray Write-Host "than a previously created RAR file ($formattedRarFileSize) with smaller dictionary size..." -ForegroundColor DarkGray Write-Host "Deleting file: `"$($outputRarFile.Name)`" ($formattedOutputRarFileSize)..." -ForegroundColor Yellow if ($sendRarFilesToRecycleBin) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') } else { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'DeletePermanently') } Write-Host "Deletion completed." -ForegroundColor Yellow } } } } } if (Test-Path -LiteralPath $outputRarFile.FullName -PathType Leaf) { $createdRarFiles.Add($outputRarFile) } Write-Host "" } if ($keepOnlySmallestRarFile -and $createdRarFiles.Count -gt 0) { $existingFiles = $createdRarFiles | Where-Object { $_.Exists } if ($existingFiles.Count -gt 0) { Write-Host "`$keepOnlySmallestRarFile variable is `$True. Comparing file sizes of created RAR files..." -ForegroundColor Yellow Write-Host "" $smallestFile = $existingFiles | Sort-Object Length | Select-Object -First 1 foreach ($file in $existingFiles) { if ($file -ne $smallestFile) { $formattedFileSize = Format-FileSize -fileSize $file.Length Write-Host "Deleting file: `"$($file.Name)`" ($formattedFileSize)..." -ForegroundColor Yellow if ($sendRarFilesToRecycleBin) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') } else { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'DeletePermanently') } Write-Host "Deletion completed." -ForegroundColor Yellow Write-Host "" } } $formattedSmallestFileSize = Format-FileSize -fileSize $smallestFile.Length Write-Host "Smallest file kept: $($smallestFile.Name) ($formattedSmallestFileSize)" -ForegroundColor Green Write-Host "" } } } } function Format-FileSize { param( [long]$fileSize ) $buffer = New-Object System.Text.StringBuilder 260 [Win32Functions]::StrFormatByteSizeW($fileSize, $buffer, $buffer.Capacity) | Out-Null return $buffer.ToString() } 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 = "RAR Multi-Compression Test Tool (Files) - by Elektro" #[System.Console]::SetWindowSize(150, 45) [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Confirm-Continue Compress-Files Show-GoodbyeScreen
|
|
|
123
|
Programación / Scripting / [APORTE] [PowerShell] RAR.exe | Multi-Compression Test Tool (Para Directorios)
|
en: 2 Marzo 2024, 12:47 pm
|
El siguiente script desarrollado en PowerShell y dependiente del programa externo RAR.exe (WinRAR), sirve para comprimir cada directorio dentro del directorio actual de forma individual, con compresión máxima, y utilizando los tamaños de diccionario especificados. La sección "Variables" dentro del script permite configurar varias cosas, entre ellas: - Los tamaños de diccionario. - Las extensiones de archivo que se deben procesar sin aplicar compresión. - Preservar solamente el archivo RAR generado con el menor tamaño de todos. (eliminar los archivos RAR de mayor tamaño) - Especificar una diferencia de tamaño (tolerancia) arbitraria para eliminar archivos RAR generados (con mayores tamaños de diccionario) de un tamaño de archivo similar. - Enviar los archivos RAR eliminados a la papelera de reciclaje. Es muy útil, por ejemplo, para comprimir de forma automatizada directorios de video juegos para PC y obtener así el mejor resultado entre Tamaño de diccionario / Tamaño de archivo.
<# =========================================================================================== | | | Variables | | | =========================================================================================== #> $rarExecutablePath = "C:\Program Files\WinRAR\rar.exe" $dictionarySizes = @(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048) $toleranceSizeDiff = "1MB" $keepOnlySmallestRarFile = $true $sendRarFilesToRecycleBin = $false $compressedFileTypesArchive = @( "7z" , "arc", "bz2" , "bzip", "bzip2", "gz" , "gz2", "gza" , "gzi" , "gzip" , "lha", "lz" , "lz4" , "lzh" , "lzma" , "rar", "sfx", "tgz" , "tlz" , "tlzma", "uha", "zip", "zipx", "zpaq" ) $compressedFileTypesAudio = @( "aac", "ac3", "fla","flac", "m4a", "mp3", "ogg", "ogm", "usm", "wma" ) $compressedFileTypesVideo = @( "asf", "avc", "avi" , "bik" , "bk2" , "f4v" , "flv" , "m1v", "m2t", "m2ts", "m2v" , "m4v" , "mpv4", "mkv", "mov", "mp4" , "mpeg", "mpg" , "mts" , "qt" , "ts" , "vob" , "vp6" , "webm", "wmv" ) $compressedFileTypesOther = @( "avif", "jpeg", "jpg" , "gif" , "pdf", "pam" , "paq6", "paq7", "paq8", "par" , "par2", "wad" ) [string]$fileTypesToKeepUncompressed = ( $compressedFileTypesArchive + $compressedFileTypesAudio + $compressedFileTypesVideo + $compressedFileTypesOther ) -join ';' <# =========================================================================================== | | | rar.exe commands (only those used in this script) | | | =========================================================================================== <Commands> a Add files to archive <Switches> -am[s,r] Archive name and time [save, restore] -c- Disable comments show -cfg- Ignore configuration file and RAR environment variable. -dh Open shared files -ep1 Exclude base directory from names -ht[b|c] Select hash type [BLAKE2,CRC32] for file checksum -id[c,d,n,p,q] Display or disable messages -ilog[name] Log errors to file -isnd[-] Control notification sounds -m<0..5> Set compression level (0-store...3-default...5-maximal) -ma[4|5] Specify a version of archiving format -md<n>[k,m,g] Dictionary size in KB, MB or GB -ms[list] Specify file types to store. -o[+|-] Set the overwrite mode -oc Set NTFS Compressed attribute. -oh Save hard links as the link instead of the file -oi[0-4][:min] Save identical files as references -ol[a] Process symbolic links as the link [absolute paths] -oni Allow potentially incompatible names -qo[-|+] Add quick open information [none|force] -r Recurse subdirectories -ri<P>[:<S>] Set priority (0-default,1-min..15-max) and sleep time in ms -s- Disable solid archiving -t Test files after archiving -tk Keep original archive time -tl Set archive time to newest file -ts[m,c,a,p] Save or restore time (modification, creation, access, preserve) -u Update files -w<path> Assign work directory #> <# =========================================================================================== | | | .NET Code | | | =========================================================================================== #> Add-Type -TypeDefinition @" using System; using System.Runtime.InteropServices; public class Win32Functions { [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)] public static extern long StrFormatByteSizeW(long fileSize, System.Text.StringBuilder buffer, int bufferSize); } "@ <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +==========================================================+" Write-Host " | |" Write-Host " | This script will use RAR.exe to compress each directory |" Write-Host " | in the current working directory individually, each |" Write-Host " | using different dictionary sizes, with max. compression, |" Write-Host " | generating this way multiple RAR files for evaluating |" Write-Host " | compression rates on these dictionary sizes. |" Write-Host " | |" Write-Host " +==========================================================+" Write-Host "" Write-Host " Script Settings " -ForegroundColor DarkGray Write-Host " ===========================" -ForegroundColor DarkGray Write-Host " RAR Executable Path: $([System.IO.Path]::GetFullPath($rarExecutablePath))" -ForegroundColor Gray Write-Host "" -ForegroundColor DarkGray Write-Host " Dictionary Sizes (Megabyte): $($dictionarySizes -join ', ')" -ForegroundColor Gray Write-Host " The script will create a RAR archive for each specified dictionary size." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " File Types To Keep Uncompressed: `$keepCompressedFileTypesUncompressed" -ForegroundColor Gray Write-Host " The script will instruct RAR to don't compress the specified known compressed file types." -ForegroundColor DarkGray Write-Host " (See `$keepCompressedFileTypesUncompressed variable definition to manage the file types)" -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Tolerance File Size Difference: $toleranceSizeDiff" -ForegroundColor Gray Write-Host " Any newly created RAR file whose file size compared to previously " -ForegroundColor DarkGray Write-Host " created RAR files is within the specified tolerance value, it will be deleted." -ForegroundColor DarkGray Write-Host " For example, if `$toleranceSizeDiff value is 1MB:" -ForegroundColor DarkGray Write-Host " If a created RAR file of 32 MB dict. size has a file size of 100 MB," -ForegroundColor DarkGray Write-Host " and then a newly created RAR file of 64 MB dict. size has a file size of 99 MB, " -ForegroundColor DarkGray Write-Host " the RAR file of 64 MB dict. size will be deleted because it only differs in 1MB or less." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Keep only smallest rar file: $keepOnlySmallestRarFile" -ForegroundColor Gray Write-Host " If True, the script will delete any newly created RAR file " -ForegroundColor DarkGray Write-Host " whose file size is bigger than previously created RAR files." -ForegroundColor DarkGray Write-Host " Note: it takes into account the specified `$toleranceSizeDiff value." -ForegroundColor DarkGray Write-Host "" -ForegroundColor DarkGray Write-Host " Send RAR files to recycle bin: $sendRarFilesToRecycleBin" -ForegroundColor Gray Write-Host " If True, the script will send RAR files to recycle bin instead of permanently deleting them." -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)} else {Clear-Host} } function Compress-Files { Add-Type -AssemblyName Microsoft.VisualBasic $dictionarySizes = $dictionarySizes | Sort-Object # Partir y formatear la cadena de file types para acomodarlo a la linea de argumentos de rar.exe if (-not [String]::IsNullOrEmpty($fileTypesToKeepUncompressed)) { $fileTypeTokens = $fileTypesToKeepUncompressed -split ';' $fileTypesArgumentLines = @() for ($i = 0; $i -lt $fileTypeTokens.Count; $i += 20) { $fileTypesArgumentLines += "-ms" + ($fileTypeTokens[$i..($i + 19)] -join ';') + [Environment]::NewLine } if ($fileTypesArgumentLines.Count -gt 0) { $fileTypesArgumentLines[-1] = $fileTypesArgumentLines[-1] -replace [Environment]::NewLine, '' } } else { $fileTypesArgumentLines = "-ms " } foreach ($dir in Get-ChildItem -LiteralPath "$PSScriptRoot" -Directory) { $dirSizeBytes = (Get-ChildItem -LiteralPath "$($dir.FullName)" -Recurse | Measure-Object -Property Length -sum).Sum # Keeps track of created rar files by rar.exe $createdRarFiles = New-Object System.Collections.Generic.List[System.IO.FileInfo] foreach ($size in $dictionarySizes) { if (($size -ne $dictionarySizes[0]) -and ($dirSizeBytes * 4) -le ($size * 1MB)) { $formattedDirSize = Format-FileSize -fileSize $dirSizeBytes Write-Host "Ignoring compression with too big dictionary size of $size mb for a $formattedDirSize directory: `"$($dir.FullName)`"..." -ForegroundColor Yellow continue } $outputRarFilePath = "$($dir.FullName)_$($size)mb.rar" $errorLogFilePath = "$($dir.FullName)_$($size)mb_error.log" $arguments = @( " a -u -ams -c- -cfg- -dh -ep1 -htb -idcdn -isnd- -iver -m5 -ma5 -md$($size)m", " -o+ -oc -oh -oi2 -ol -oni -qo+ -r -ri0:0 -s- -t -tk -tl -tsmca+", " $fileTypesArgumentLines", " -x`"*\$($MyInvocation.MyCommand.Name)`"", " -w`"$($env:TEMP)`"", " -ilog`"$errorLogFilePath`"", " -- `"$outputRarFilePath`"", " -- `"$($dir.FullName)\*`"" ) Write-Host "Compressing directory with $size mb dictionary dize: `"$($dir.Name)`"..." #Write-Host "" #Write-Host "rar.exe arguments:" -ForegroundColor DarkGray #Write-Host ($arguments -join [Environment]::NewLine) -ForegroundColor DarkGray $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $rarExecutablePath $psi.Arguments = $arguments -join ' ' $psi.RedirectStandardOutput = $false $psi.UseShellExecute = $false $psi.CreateNoWindow = $false $process = [System.Diagnostics.Process]::Start($psi) $process.WaitForExit() $outputRarFile = New-Object System.IO.FileInfo($outputRarFilePath) $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length Write-Host "" Write-Host "Created rar with file name: $($outputRarFile.Name) ($formattedOutputRarFileSize)" -ForegroundColor DarkGreen if ($toleranceSizeDiff -ne $null) { if ($createdRarFiles.Count -ne 0) { $outputRarFileMB = [Math]::Floor($outputRarFile.Length / $toleranceSizeDiff) $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length foreach ($rarFile in $createdRarFiles) { if ($rarFile.Exists) { $sizeMB = [Math]::Floor($rarFile.Length / $toleranceSizeDiff) $formattedRarFileSize = Format-FileSize -fileSize $rarFile.Length if ($outputRarFileMB -eq $sizeMB) { Write-Host "" Write-Host "File size of this created RAR file ($formattedOutputRarFileSize) is within the $toleranceSizeDiff tolerance difference" -ForegroundColor DarkGray Write-Host "than a previously created RAR file ($formattedRarFileSize) with smaller dictionary size..." -ForegroundColor DarkGray Write-Host "Deleting file: `"$($outputRarFile.Name)`" ($formattedOutputRarFileSize)..." -ForegroundColor Yellow if ($sendRarFilesToRecycleBin) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') } else { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'DeletePermanently') } Write-Host "Deletion completed." -ForegroundColor Yellow } } } } } if (Test-Path -LiteralPath $outputRarFile.FullName -PathType Leaf) { $createdRarFiles.Add($outputRarFile) } Write-Host "" } if ($keepOnlySmallestRarFile -and $createdRarFiles.Count -gt 0) { $existingFiles = $createdRarFiles | Where-Object { $_.Exists } if ($existingFiles.Count -gt 0) { Write-Host "`$keepOnlySmallestRarFile variable is `$True. Comparing file sizes of created RAR files..." -ForegroundColor Yellow Write-Host "" $smallestFile = $existingFiles | Sort-Object Length | Select-Object -First 1 foreach ($file in $existingFiles) { if ($file -ne $smallestFile) { $formattedFileSize = Format-FileSize -fileSize $file.Length Write-Host "Deleting file: `"$($file.Name)`" ($formattedFileSize)..." -ForegroundColor Yellow if ($sendRarFilesToRecycleBin) { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin') } else { [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'DeletePermanently') } Write-Host "Deletion completed." -ForegroundColor Yellow Write-Host "" } } $formattedSmallestFileSize = Format-FileSize -fileSize $smallestFile.Length Write-Host "Smallest file kept: $($smallestFile.Name) ($formattedSmallestFileSize)" -ForegroundColor Green Write-Host "" } } } } function Format-FileSize { param( [long]$fileSize ) $buffer = New-Object System.Text.StringBuilder 260 [Win32Functions]::StrFormatByteSizeW($fileSize, $buffer, $buffer.Capacity) | Out-Null return $buffer.ToString() } 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 = "RAR Multi-Compression Test Tool (Directories) - by Elektro" #[System.Console]::SetWindowSize(150, 45) [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Confirm-Continue Compress-Files Show-GoodbyeScreen
|
|
|
124
|
Programación / .NET (C#, VB.NET, ASP) / Re: crear / compilar en windows - ejecutar en linux
|
en: 2 Marzo 2024, 11:57 am
|
¿A estas alturas de la vida? A estas alturas de la vida, Xamarin sigue sin ofrecer soporte para programar directamente en el lenguaje VB.NET, por ejemplo. Y creo que con la tecnología multiplataforma .NET MAUI sucede lo mismo. Hay cosas que simplemente no tienen la suficiente demanda o no les da la gana realizar el trabajo necesario para ofrecer soporte...
Respondiendo a tu duda principal y hasta donde yo se, ya lo respondí en mi aterior comentario pero lo diré de otra forma: no es posible desarrollar una aplicación de escritorio basada en Windows Forms de .NET Core y que sea compatible con Linux. Al menos no de forma nativa sin recurrir a Wine o cosas similares. Aténtamente, Elektro.
|
|
|
125
|
Foros Generales / Sugerencias y dudas sobre el Foro / PowerShell: Web Application Firewall (WAF) Blocked | Una regla de seguridad ha sido aplicada...
|
en: 2 Marzo 2024, 11:07 am
|
Hola. Abro este hilo por que he descubierto que al intentar publicar un post con el siguiente código escrito en el lenguaje Powershell: $rarExecutablePath = "$ {env:ProgramFiles}\WinRAR\rar.exe" (Nótese el espacio en blanco que he tenido que poner en la cadena " $ {env" para poder publicar este post.) Me redirige a una página con el siguiente mensaje: Web Application Firewall (WAF) Blocked Una regla de seguridad ha sido aplicada. Si crees que es un error (falso positivo) contacta con webmaster@elhacker.net - Gracias. The action you just performed triggered the security solution. If you think is false positive please contact to webmaster@elhacker.net - Thank you No se si tendrá solución, simplemente lo comunico por si pudieran hacer algo con ello. PD: Si no mando un e-mail a webmaster@elhacker.net es por que tal vez mi cuenta de correo esté bloqueada. Aténtamente, Elektro.
|
|
|
126
|
Programación / Scripting / [APORTE] [PowerShell] RAR.exe | Listar version y tamaño de diccionario utilizado
|
en: 2 Marzo 2024, 11:03 am
|
El siguiente script desarrollado en PowerShell y dependiente del programa externo RAR.exe (WinRAR), sirve para listar la version de RAR/WinRAR y el tamaño de diccionario utilizado para la compresión de cada archivo RAR dentro del directorio actual. <# =========================================================================================== | | | Variables | | | =========================================================================================== #> $rarExecutablePath = "C:\Program Files\WinRAR\rar.exe" <# =========================================================================================== | | | Functions | | | =========================================================================================== #> function Show-WelcomeScreen { Clear-Host Write-Host "" Write-Host " $($host.ui.RawUI.WindowTitle)" Write-Host " +==========================================================+" Write-Host " | |" Write-Host " | This script will use RAR.exe to analyze each RAR file in |" Write-Host " | the current working directory (including subdirectories) |" Write-Host " | and print the RAR version and dictionary size used for |" Write-Host " | compression. |" Write-Host " | |" Write-Host " +==========================================================+" Write-Host "" Write-Host " Script Settings " -ForegroundColor DarkGray Write-Host " ===========================" -ForegroundColor DarkGray Write-Host " RAR Executable Path: $([System.IO.Path]::GetFullPath($rarExecutablePath))" -ForegroundColor Gray 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)} else {Clear-Host} } function Test-RarFiles { $rarFiles = Get-ChildItem -LiteralPath "$PSScriptRoot" -Recurse -Filter "*.rar" foreach ($rarFile in $rarFiles) { $p = New-Object System.Diagnostics.Process $p.StartInfo.FileName = $rarExecutablePath $p.StartInfo.Arguments = "lt `"$($rarFile.FullName)`"" $p.StartInfo.UseShellExecute = $false $p.StartInfo.RedirectStandardOutput = $true $p.Start() | Out-Null while (!$p.StandardOutput.EndOfStream ) { $line = $p.StandardOutput.ReadLine() if ($line -match "-md=") { Write-Host "$($rarFile.FullName)" -ForegroundColor White Write-Host "RAR Version: $($line.Split(' ')[3])" -ForegroundColor Yellow Write-Host "Dict. Sizes: $($line.Split(' ')[5].Replace('-md=', ''))" -ForegroundColor Yellow Write-Host "" try { $p.Kill() } catch {} break } } $p.WaitForExit() } } 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 = "List RAR Versions and Dictionary Sizes - by Elektro" #[System.Console]::SetWindowSize(150, 45) [CultureInfo]::CurrentUICulture = "en-US" try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { } Show-WelcomeScreen Confirm-Continue Test-RarFiles Show-GoodbyeScreen
|
|
|
127
|
Foros Generales / Foro Libre / Re: Whatsapp: ¿Puede una mafia de ciberestafadores hacer algo solo por haberles enviado un mensaje de texto?
|
en: 29 Febrero 2024, 03:04 am
|
¿que fue lo que te interesó de esa oferta de trabajo para que respondas? A diferencia de otras veces, le atribuí cierta verosimilitud por dos motivos. El primero es que la persona que me habló se hizo pasar por el CEO de una empresa relacionada con el desarrollo de software (no daré nombres, pero una empresa pequeña en Francia; tuve que buscarla en Google por que no la conocía), y el segundo motivo es que últimamente me estoy esforzando en intentar aumentar mi visibilidad para captar ese tipo de ofertas de trabajo. Al parecer estas mafias saben demasiados datos sobre los intereses de sus potenciales víctimas. Quiero decir, si una persona no tiene una cuenta en el banco "X", probablemente estas mafias lo sabrán y no te enviarán un mensaje suplantando a ese banco, sino que te investigarán más a fondo para saber exactamente que banco utilizas y así hacer mejor ingenieria social contigo. Es solo un ejemplo, y supongo que será algo obvio.
En fin. Yo también me alegro de volver a intercambiar unas palabras con todos los que hayan participado y participen en este hilo ya sea con la intención de hacer un comentario amistoso de bienvenida y reencuentro a mi vuelta al foro, y/o de contribuir y enriquecer el debate hablando del asunto en cuestión del que hay que hablar, que no soy yo ni los conflictos que haya tenido en el foro ni las sanciones, sino los estafadores, Pegasus y demás cosas relacionadas. Aténtamente, Elektro.
|
|
|
129
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 28 Febrero 2024, 17:13 pm
|
Dos métodos que manipulan el registro de Windows. El primero sirve para crear una nueva entrada en el menú contextual del explorador de Windows al hacer click derecho sobre un tipo de archivo, lo que por lo general sirve para asociar un programa a un tipo/extensión de archivo y poder cargar el archivo haciendo click en esa entrada del menú contextual. Y el segundo método sirve para borrar la entrada. Nota: el primer método sirve para crear entradas individuales, no sirve para crear submenús. ''' <summary> ''' Creates a registry key that represents a new entry in the Explorer's context-menu for the specified file type. ''' </summary> ''' ''' <param name="fileType"> ''' The file type (typically a file extension) for which to create the entry in the Explorer's context-menu. ''' </param> ''' ''' <param name="keyName"> ''' The name of the registry key. ''' </param> ''' ''' <param name="text"> ''' The display text for the entry in the Explorer's context-menu. ''' <para></para> ''' This value can be null, in which case <paramref name="keyName"/> will be used as text. ''' </param> ''' ''' <param name="position"> ''' The position of the entry in the Explorer's context-menu. ''' <para></para> ''' Valid values are: "top", "middle" and "bottom". ''' <para></para> ''' This value can be null. ''' </param> ''' ''' <param name="icon"> ''' The icon to show for the entry in the Explorer's context-menu. ''' <para></para> ''' This value can be null. ''' </param> ''' ''' <param name="command"> ''' The command to execute when the entry is clicked in the Explorer's context-menu. ''' </param> <DebuggerStepThrough> Public Shared Sub CreateFileTypeRegistryMenuEntry(fileType As String, keyName As String, text As String, position As String, icon As String, command As String) If String.IsNullOrWhiteSpace(fileType) Then Throw New ArgumentNullException(paramName:=NameOf(fileType)) End If If String.IsNullOrWhiteSpace(keyName) Then Throw New ArgumentNullException(paramName:=NameOf(keyName)) End If If String.IsNullOrWhiteSpace(command) Then Throw New ArgumentNullException(paramName:=NameOf(command)) End If If String.IsNullOrEmpty(text) Then text = keyName End If Using rootKey As RegistryKey = Registry.ClassesRoot, subKey As RegistryKey = rootKey.CreateSubKey($"{fileType}\shell\{keyName}", writable:=True), subKeyCommand As RegistryKey = subKey.CreateSubKey("command", writable:=True) subKey.SetValue("", text, RegistryValueKind.String) subKey.SetValue("icon", icon, RegistryValueKind.String) subKey.SetValue("position", position, RegistryValueKind.String) subKeyCommand.SetValue("", command, RegistryValueKind.String) End Using End Sub
''' <summary> ''' Deletes an existing registry key representing an entry in the Explorer's context-menu for the specified file type. ''' </summary> ''' ''' <param name="fileType"> ''' The file type associated with the registry entry. ''' </param> ''' ''' <param name="keyName"> ''' The name of the registry key to delete. ''' </param> ''' ''' <param name="throwOnMissingsubKey"> ''' Optional. If <see langword="True"/>, throws an exception if the registry key is not found. ''' <para></para> ''' Default value is <see langword="True"/>. ''' </param> <DebuggerStepThrough> Public Shared Sub DeleteFileTypeRegistryMenuEntry(fileType As String, keyName As String, Optional throwOnMissingsubKey As Boolean = True) If String.IsNullOrWhiteSpace(fileType) Then Throw New ArgumentNullException(paramName:=NameOf(fileType)) End If If String.IsNullOrWhiteSpace(keyName) Then Throw New ArgumentNullException(paramName:=NameOf(keyName)) End If Using rootKey As RegistryKey = Registry.ClassesRoot rootKey.DeleteSubKeyTree($"{fileType}\shell\{keyName}", throwOnMissingsubKey) End Using End Sub
|
|
|
|
|
|
|