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

 

 


Tema destacado: Arreglado, de nuevo, el registro del warzone (wargame) de EHN


  Mostrar Mensajes
Páginas: 1 2 3 4 5 [6] 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ... 1236
51  Programación / Scripting / Re: Archivo bat para borrar una entrada de registro en: 19 Marzo 2024, 08:17 am
eso ya me da más respeto, así es que lo voy a dejar así

Déjame decirte que por el simple hecho de ejecutar el batch-script que te mostré (tal y como está escrito, sin modificarlo) en mi último comentario con el programa setacl.exe que te indiqué, no va a pasar nada malo en tu PC. Esa advertencia en color rojo tengo que hacerla por pura formalidad más que por otra cosa...

Esa advertencia la tengo que poner por que en caso de que modifiques los permisos, de forma recursiva, de toda la rama "HKEY_LOCAL_MACHINE\SOFTWARE", pues, a ver, en principio no tiene por que ocurrir nada, pero siempre están los escenarios impredecibles con configuraciones específicas que acabasen provocando que ciertas aplicaciones instaladas para todos los usuarios dejasen de funcionar correctamente y, en caso de que modifiques los permisos, de forma recursiva, de toda la raíz "HKLM", pues, lo mismo, en principio no tiene por que ocurrir nada, pero siempre están los escenarios impredecibles con configuraciones específicas.

En fin. En caso de que no necesites automatizar esta tarea de borrar las claves del registro, simplemente considera utilizar el programa setacl.exe para obtener permisos de usuario sobre la clave de registro que te está dando error, y así lo solucionarás. También puedes usar 'SetACL Studio', pero te indiqué el otro programa por línea de comandos para que pudieras automatizar la tarea utilizado un script.

En cualquier caso, lo que prefieras hacer o no hacer es decisión tuya, claro está. Espero haberte podido ayudar en algo.

Hasta la próxima.
52  Foros Generales / Sugerencias y dudas sobre el Foro / Re: He publicado catorce hilos en el lugar incorrecto y de forma absurda... en: 19 Marzo 2024, 01:44 am
Gracias por la ayuda y la rapidez, todo poderoso Sayan. ;D

Un saludo a todos.
53  Programación / Scripting / Re: [APORTE] [PowerShell] RAR.exe | Multi-Compression Test Tool (Para Directorios) en: 19 Marzo 2024, 01:42 am
Comparto una versión actualizada del script. Las modificaciones se han basado en perfeccionar pequeños detalles y mejorar bastante la forma en que se compara el tamaño de los archivos ($toleranceSizeDiff).

Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $rarExecutablePath = "${env:ProgramFiles}\WinRAR\rar.exe"
  10. $dictionarySizesMb = @(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048)
  11. $toleranceSizeDiff = 500kb
  12. $keepOnlySmallestRarFile  = $true
  13. $sendRarFilesToRecycleBin = $false
  14.  
  15. $compressedFileTypesArchive = @(
  16.    "7z" , "arc", "bz2" , "bzip", "bzip2",
  17.    "gz" , "gz2", "gza" , "gzi" , "gzip" ,
  18.    "lha", "lz" , "lz4" , "lzh" , "lzma" ,
  19.    "rar", "sfx", "tgz" , "tlz" , "tlzma",
  20.    "uha", "zip", "zipx", "zpaq"
  21. )
  22.  
  23. $compressedFileTypesAudio = @(
  24.    "aac", "ac3", "fla","flac",
  25.    "m4a", "mp3", "ogg", "ogm",
  26.    "usm", "wma"
  27. )
  28.  
  29. $compressedFileTypesVideo = @(
  30.    "asf", "avc", "avi" , "bik" , "bk2" , "f4v" , "flv" ,
  31.    "m1v", "m2t", "m2ts", "m2v" , "m4v" , "mpv4",
  32.    "mkv", "mov", "mp4" , "mpeg", "mpg" , "mts" ,
  33.    "qt" , "ts" , "vob" , "vp6" , "webm", "wmv"
  34. )
  35.  
  36. $compressedFileTypesOther = @(
  37.    "avif", "jpeg", "jpg" , "gif" , "pdf",
  38.    "pam" , "paq6", "paq7", "paq8",
  39.    "par" , "par2", "wad"
  40. )
  41.  
  42.  
  43. [string]$fileTypesToKeepUncompressed = (
  44.    $compressedFileTypesArchive +
  45.    $compressedFileTypesAudio +
  46.    $compressedFileTypesVideo +
  47.    $compressedFileTypesOther
  48. ) -join ';'
  49.  
  50. <#
  51. ===========================================================================================
  52. |                                                                                         |
  53. |                    rar.exe commands (only those used in this script)                    |
  54. |                                                                                         |
  55. ===========================================================================================
  56.  
  57. <Commands>
  58.  a             Add files to archive
  59.  
  60. <Switches>
  61.  -am[s,r]       Archive name and time [save, restore]
  62.  -c-            Disable comments show
  63.  -cfg-          Ignore configuration file and RAR environment variable.
  64.  -dh            Open shared files
  65.  -ep1           Exclude base directory from names
  66.  -ht[b|c]       Select hash type [BLAKE2,CRC32] for file checksum
  67.  -id[c,d,n,p,q] Display or disable messages
  68.  -ilog[name]    Log errors to file
  69.  -isnd[-]       Control notification sounds
  70.  -m<0..5>       Set compression level (0-store...3-default...5-maximal)
  71.  -ma[4|5]       Specify a version of archiving format
  72.  -md<n>[k,m,g]  Dictionary size in KB, MB or GB
  73.  -ms[list]      Specify file types to store.
  74.  -o[+|-]        Set the overwrite mode
  75.  -oc            Set NTFS Compressed attribute.
  76.  -oh            Save hard links as the link instead of the file
  77.  -oi[0-4][:min] Save identical files as references
  78.  -ol[a]         Process symbolic links as the link [absolute paths]
  79.  -oni           Allow potentially incompatible names
  80.  -qo[-|+]       Add quick open information [none|force]
  81.  -r             Recurse subdirectories
  82.  -ri<P>[:<S>]   Set priority (0-default,1-min..15-max) and sleep time in ms
  83.  -s-            Disable solid archiving
  84.  -t             Test files after archiving
  85.  -tk            Keep original archive time
  86.  -tl            Set archive time to newest file
  87.  -ts[m,c,a,p]   Save or restore time (modification, creation, access, preserve)
  88.  -u             Update files
  89.  -w<path>       Assign work directory
  90. #>
  91.  
  92. <#
  93. ===========================================================================================
  94. |                                                                                         |
  95. |                                        .NET Code                                        |
  96. |                                                                                         |
  97. ===========================================================================================
  98. #>
  99.  
  100. Add-Type -TypeDefinition @"
  101. using System;
  102. using System.Runtime.InteropServices;
  103.  
  104. public class Win32Functions {
  105.    [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
  106.    public static extern long StrFormatByteSizeW(long fileSize, System.Text.StringBuilder buffer, int bufferSize);
  107. }
  108. "@
  109.  
  110. <#
  111. ===========================================================================================
  112. |                                                                                         |
  113. |                                    Functions                                            |
  114. |                                                                                         |
  115. ===========================================================================================
  116. #>
  117. function Format-FileSize {
  118.    param(
  119.        [long]$fileSize
  120.    )
  121.    $buffer = New-Object System.Text.StringBuilder 260
  122.    [Win32Functions]::StrFormatByteSizeW($fileSize, $buffer, $buffer.Capacity) | Out-Null
  123.    return $buffer.ToString()
  124. }
  125.  
  126. function Show-WelcomeScreen {
  127.    Clear-Host
  128.    Write-Host ""
  129.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  130.    Write-Host " +==========================================================+"
  131.    Write-Host " |                                                          |"
  132.    Write-Host " | This script will use RAR.exe to compress each directory  |"
  133.    Write-Host " | in the current working directory individually, each      |"
  134.    Write-Host " | using different dictionary sizes, with max. compression, |"
  135.    Write-Host " | generating this way multiple RAR files for evaluating    |"
  136.    Write-Host " | compression rates on these dictionary sizes.             |"
  137.    Write-Host " |                                                          |"
  138.    Write-Host " +==========================================================+"
  139.    Write-Host ""
  140.    Write-Host " Script Settings            " -ForegroundColor DarkGray
  141.    Write-Host " ===========================" -ForegroundColor DarkGray
  142.    Write-Host " RAR Executable Path: $([System.IO.Path]::GetFullPath($rarExecutablePath))" -ForegroundColor Gray
  143.    Write-Host "" -ForegroundColor DarkGray
  144.    Write-Host " Dictionary Sizes (Megabyte): $($dictionarySizesMb -join ', ')" -ForegroundColor Gray
  145.    Write-Host " The script will create a RAR archive for each specified dictionary size." -ForegroundColor DarkGray
  146.    Write-Host "" -ForegroundColor DarkGray
  147.    Write-Host " File Types To Keep Uncompressed: `$keepCompressedFileTypesUncompressed" -ForegroundColor Gray
  148.    Write-Host " The script will instruct RAR to don't compress the specified known compressed file types." -ForegroundColor DarkGray
  149.    Write-Host " (See `$keepCompressedFileTypesUncompressed variable definition to manage the file types)" -ForegroundColor DarkGray
  150.    Write-Host "" -ForegroundColor DarkGray
  151.    Write-Host " Tolerance File Size Difference: $(Format-FileSize -fileSize $toleranceSizeDiff)" -ForegroundColor Gray
  152.    Write-Host " Any newly created RAR file whose file size compared to previously   " -ForegroundColor DarkGray
  153.    Write-Host " created RAR files is within the specified tolerance value, it will be deleted." -ForegroundColor DarkGray
  154.    Write-Host " For example, if `$toleranceSizeDiff value is 1MB:" -ForegroundColor DarkGray
  155.    Write-Host " If a created RAR file of 32 MB dict. size has a file size of 100 MB," -ForegroundColor DarkGray
  156.    Write-Host " and then a newly created RAR file of 64 MB dict. size has a file size of 99 MB, " -ForegroundColor DarkGray
  157.    Write-Host " the RAR file of 64 MB dict. size will be deleted because it only differs in 1MB or less." -ForegroundColor DarkGray
  158.    Write-Host "" -ForegroundColor DarkGray
  159.    Write-Host " Keep only smallest RAR file: $keepOnlySmallestRarFile" -ForegroundColor Gray
  160.    Write-Host " If True, the script will delete any newly created RAR file " -ForegroundColor DarkGray
  161.    Write-Host " whose file size is bigger than previously created RAR files." -ForegroundColor DarkGray
  162.    Write-Host " Note: it takes into account the specified `$toleranceSizeDiff value." -ForegroundColor DarkGray
  163.    Write-Host "" -ForegroundColor DarkGray
  164.    Write-Host " Send RAR files to recycle bin: $sendRarFilesToRecycleBin" -ForegroundColor Gray
  165.    Write-Host " If True, the script will send RAR files to recycle bin instead of permanently deleting them." -ForegroundColor DarkGray
  166.    Write-Host ""
  167. }
  168.  
  169. function Confirm-Continue {
  170.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  171.    Write-Host ""
  172.    Write-Host " -Continue? (Y/N)"
  173.    do {
  174.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  175.        $char = $key.Character.ToString().ToUpper()
  176.        if ($char -ne "Y" -and $char -ne "N") {
  177.            [console]::beep(1500, 500)
  178.        }
  179.    } while ($char -ne "Y" -and $char -ne "N")
  180.    if ($char -eq "N") {Exit(1)} else {Clear-Host}
  181. }
  182.  
  183. function Compress-Files {
  184.    Add-Type -AssemblyName Microsoft.VisualBasic
  185.  
  186.    $dictionarySizesMb = $dictionarySizesMb | Sort-Object
  187.  
  188.    # Partir y formatear la cadena de file types para acomodarlo a la linea de argumentos de rar.exe
  189.    if (-not [String]::IsNullOrEmpty($fileTypesToKeepUncompressed)) {
  190.        $fileTypeTokens = $fileTypesToKeepUncompressed -split ';'
  191.        $fileTypesArgumentLines = @()
  192.        for ($i = 0; $i -lt $fileTypeTokens.Count; $i += 20) {
  193.            $fileTypesArgumentLines += "-ms" + ($fileTypeTokens[$i..($i + 19)] -join ';') + [Environment]::NewLine
  194.        }
  195.        if ($fileTypesArgumentLines.Count -gt 0) {
  196.            $fileTypesArgumentLines[-1] = $fileTypesArgumentLines[-1] -replace [Environment]::NewLine, ''
  197.        }
  198.    } else {
  199.        $fileTypesArgumentLines = "-ms "
  200.    }
  201.  
  202.    foreach ($dir in Get-ChildItem -LiteralPath "$PSScriptRoot" -Directory) {
  203.  
  204.        $dirSizeBytes = (Get-ChildItem -LiteralPath "$($dir.FullName)" -Recurse | Measure-Object -Property Length -sum).Sum
  205.  
  206.        # Keeps track of created rar files by rar.exe
  207.        $createdRarFiles = New-Object System.Collections.Generic.List[System.IO.FileInfo]
  208.  
  209.        foreach ($size in $dictionarySizesMb) {
  210.  
  211.            if (($size -ne $dictionarySizesMb[0]) -and ($dirSizeBytes * 4) -le ($size * 1MB)) {
  212.                $formattedDirSize = Format-FileSize -fileSize $dirSizeBytes
  213.                Write-Host "Ignoring compression with too big dictionary size of $size mb for a $formattedDirSize directory: `"$($dir.FullName)`"..." -ForegroundColor Yellow
  214.                continue
  215.            }
  216.  
  217.            $outputRarFilePath   = "$($dir.FullName)_$($size)mb.rar"
  218.            $errorLogFilePath = "$($dir.FullName)_$($size)mb_error.log"
  219.  
  220.            $arguments = @(
  221.                " a -u -ams -c- -cfg- -dh -ep1 -htb -idcdn -isnd- -iver -m5 -ma5 -md$($size)m",
  222.                " -o+ -oc -oh -oi2 -ol -oni -qo+ -r -ri0:0 -s- -t -tk -tl -tsmca+",
  223.                " $fileTypesArgumentLines",
  224.                " -x`"*\$($MyInvocation.MyCommand.Name)`"",
  225.                " -w`"$($env:TEMP)`"",
  226.                " -ilog`"$errorLogFilePath`"",
  227.                " -- `"$outputRarFilePath`"",
  228.                " -- `"$($dir.FullName)\*`""
  229.            )
  230.  
  231.            Write-Host "Compressing directory with $size mb dictionary size: `"$($dir.Name)`"..."
  232.            #Write-Host ""
  233.            #Write-Host "rar.exe arguments:" -ForegroundColor DarkGray
  234.            #Write-Host ($arguments -join [Environment]::NewLine) -ForegroundColor DarkGray
  235.  
  236.            $previousForegroundColor = $host.UI.RawUI.ForegroundColor
  237.            $host.UI.RawUI.ForegroundColor = "DarkGray"
  238.            $psi = New-Object System.Diagnostics.ProcessStartInfo
  239.            $psi.FileName = $rarExecutablePath
  240.            $psi.Arguments = $arguments -join ' '
  241.            $psi.RedirectStandardOutput = $false
  242.            $psi.UseShellExecute = $false
  243.            $psi.CreateNoWindow = $false
  244.  
  245.            $process = [System.Diagnostics.Process]::Start($psi)
  246.            $process.WaitForExit()
  247.            $host.UI.RawUI.ForegroundColor = $previousForegroundColor
  248.  
  249.            $outputRarFile = New-Object System.IO.FileInfo($outputRarFilePath)
  250.            $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length
  251.            Write-Host ""
  252.            Write-Host "Created rar with file name: $($outputRarFile.Name) ($formattedOutputRarFileSize) ($($outputRarFile.Length) bytes)" -ForegroundColor DarkGreen
  253.  
  254.            if ($toleranceSizeDiff -ne $null) {
  255.                if ($createdRarFiles.Count -ne 0) {
  256.                    $outputRarFileSize = $outputRarFile.Length
  257.                    $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFileSize
  258.                    $formattedToleranceFileSize = Format-FileSize -fileSize $toleranceSizeDiff
  259.  
  260.                    foreach ($createdRarFile in $createdRarFiles) {
  261.                        if ($createdRarFile.Exists) {
  262.                            $createdRarFileSize = $createdRarFile.Length
  263.                            $formattedCreatedRarFileSize = Format-FileSize -fileSize $createdRarFileSize
  264.                            $diffSize = [Math]::Abs($createdRarFileSize - $outputRarFileSize)
  265.                            $formattedDiffSize = Format-FileSize -fileSize $diffSize
  266.  
  267.                            if (($outputRarFileSize + $toleranceSizeDiff) -ge $createdRarFileSize) {
  268.                                Write-Host ""
  269.                                Write-Host "Size of this created RAR file ($formattedOutputRarFileSize) ($outputRarFileSize bytes) is within the $formattedToleranceFileSize tolerance difference" -ForegroundColor Yellow
  270.                                Write-Host "than a previously created RAR file of $formattedCreatedRarFileSize ($createdRarFileSize bytes) with smaller dictionary size..." -ForegroundColor Yellow
  271.                                Write-Host "Size of this created RAR file only differs by $formattedDiffSize ($diffSize bytes)." -ForegroundColor Yellow
  272.                                Write-Host "Deleting file: `"$($outputRarFile.Name)`"..." -ForegroundColor Yellow
  273.                                if ($sendRarFilesToRecycleBin) {
  274.                                    [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  275.                                } else {
  276.                                    [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'DeletePermanently')
  277.                                }
  278.                                Write-Host "Deletion completed." -ForegroundColor Yellow
  279.                                break
  280.                            }
  281.                        }
  282.                    }
  283.                }
  284.            }
  285.  
  286.            if (Test-Path -LiteralPath $outputRarFile.FullName -PathType Leaf) {
  287.                $createdRarFiles.Add($outputRarFile)
  288.            }
  289.            Write-Host ""
  290.        }
  291.  
  292.        if ($keepOnlySmallestRarFile -and $createdRarFiles.Count -gt 0) {
  293.            $existingFiles = $createdRarFiles | Where-Object { $_.Exists }
  294.            if ($existingFiles.Count -gt 0) {
  295.                Write-Host "`$keepOnlySmallestRarFile variable is `$True. Comparing file sizes of created RAR files..." -ForegroundColor Yellow
  296.                Write-Host ""
  297.                $smallestFile = $existingFiles | Sort-Object Length | Select-Object -First 1
  298.                foreach ($file in $existingFiles) {
  299.                    if ($file -ne $smallestFile) {
  300.                        $formattedFileSize = Format-FileSize -fileSize $file.Length
  301.                        Write-Host "Deleting file: `"$($file.Name)`" ($formattedFileSize)..." -ForegroundColor Yellow
  302.                        if ($sendRarFilesToRecycleBin) {
  303.                            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  304.                        } else {
  305.                            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'DeletePermanently')
  306.                        }
  307.                        Write-Host "Deletion completed." -ForegroundColor Yellow
  308.                        Write-Host ""
  309.                    }
  310.                }
  311.                $formattedSmallestFileSize = Format-FileSize -fileSize $smallestFile.Length
  312.                Write-Host "Smallest file kept: $($smallestFile.Name) ($formattedSmallestFileSize)" -ForegroundColor Green
  313.                Write-Host ""
  314.            }
  315.        }
  316.  
  317.    }
  318. }
  319.  
  320. function Show-GoodbyeScreen {
  321.    Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  322.    Write-Host ""
  323.    Write-Host "Press any key to exit..."
  324.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  325.    Exit(0)
  326. }
  327.  
  328. <#
  329. ===========================================================================================
  330. |                                                                                         |
  331. |                                         Main                                            |
  332. |                                                                                         |
  333. ===========================================================================================
  334. #>
  335.  
  336. [System.Console]::Title = "RAR Multi-Compression Test Tool (Directories) - by Elektro"
  337. #[System.Console]::SetWindowSize(150, 45)
  338. [CultureInfo]::CurrentUICulture = "en-US"
  339.  
  340. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  341.  
  342. Show-WelcomeScreen
  343. Confirm-Continue
  344. Compress-Files
  345. Show-GoodbyeScreen
  346.  
54  Programación / Scripting / Re: [APORTE] [PowerShell] RAR.exe | Multi-Compression Test Tool (Para Archivos) en: 19 Marzo 2024, 01:42 am
Comparto una versión actualizada del script. Las modificaciones se han basado en perfeccionar pequeños detalles y mejorar bastante la forma en que se compara el tamaño de los archivos ($toleranceSizeDiff).

Código
  1. <#
  2. ===========================================================================================
  3. |                                                                                         |
  4. |                                        Variables                                        |
  5. |                                                                                         |
  6. ===========================================================================================
  7. #>
  8.  
  9. $rarExecutablePath = "${env:ProgramFiles}\WinRAR\rar.exe"
  10. $dictionarySizesMb = @(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048)
  11. $toleranceSizeDiff = 100kb
  12. $keepOnlySmallestRarFile  = $true
  13. $sendRarFilesToRecycleBin = $false
  14.  
  15. $compressedFileTypesArchive = @(
  16.    "7z" , "arc", "bz2" , "bzip", "bzip2",
  17.    "gz" , "gz2", "gza" , "gzi" , "gzip" ,
  18.    "lha", "lz" , "lz4" , "lzh" , "lzma" ,
  19.    "rar", "sfx", "tgz" , "tlz" , "tlzma",
  20.    "uha", "zip", "zipx", "zpaq"
  21. )
  22.  
  23. $compressedFileTypesAudio = @(
  24.    "aac", "ac3", "fla","flac",
  25.    "m4a", "mp3", "ogg", "ogm",
  26.    "usm", "wma"
  27. )
  28.  
  29. $compressedFileTypesVideo = @(
  30.    "asf", "avc", "avi" , "bik" , "bk2" , "f4v" , "flv" ,
  31.    "m1v", "m2t", "m2ts", "m2v" , "m4v" , "mpv4",
  32.    "mkv", "mov", "mp4" , "mpeg", "mpg" , "mts" ,
  33.    "qt" , "ts" , "vob" , "vp6" , "webm", "wmv"
  34. )
  35.  
  36. $compressedFileTypesOther = @(
  37.    "avif", "jpeg", "jpg" , "gif" , "pdf",
  38.    "pam" , "paq6", "paq7", "paq8",
  39.    "par" , "par2", "wad"
  40. )
  41.  
  42.  
  43. [string]$fileTypesToKeepUncompressed = (
  44.    $compressedFileTypesArchive +
  45.    $compressedFileTypesAudio +
  46.    $compressedFileTypesVideo +
  47.    $compressedFileTypesOther
  48. ) -join ';'
  49.  
  50. <#
  51. ===========================================================================================
  52. |                                                                                         |
  53. |                    rar.exe commands (only those used in this script)                    |
  54. |                                                                                         |
  55. ===========================================================================================
  56.  
  57. <Commands>
  58.  a             Add files to archive
  59.  
  60. <Switches>
  61.  -am[s,r]       Archive name and time [save, restore]
  62.  -c-            Disable comments show
  63.  -cfg-          Ignore configuration file and RAR environment variable.
  64.  -dh            Open shared files
  65.  -ep1           Exclude base directory from names
  66.  -ht[b|c]       Select hash type [BLAKE2,CRC32] for file checksum
  67.  -id[c,d,n,p,q] Display or disable messages
  68.  -ilog[name]    Log errors to file
  69.  -isnd[-]       Control notification sounds
  70.  -m<0..5>       Set compression level (0-store...3-default...5-maximal)
  71.  -ma[4|5]       Specify a version of archiving format
  72.  -md<n>[k,m,g]  Dictionary size in KB, MB or GB
  73.  -ms[list]      Specify file types to store.
  74.  -o[+|-]        Set the overwrite mode
  75.  -oc            Set NTFS Compressed attribute.
  76.  -oh            Save hard links as the link instead of the file
  77.  -oi[0-4][:min] Save identical files as references
  78.  -ol[a]         Process symbolic links as the link [absolute paths]
  79.  -oni           Allow potentially incompatible names
  80.  -qo[-|+]       Add quick open information [none|force]
  81.  -r             Recurse subdirectories
  82.  -ri<P>[:<S>]   Set priority (0-default,1-min..15-max) and sleep time in ms
  83.  -s-            Disable solid archiving
  84.  -t             Test files after archiving
  85.  -tk            Keep original archive time
  86.  -tl            Set archive time to newest file
  87.  -ts[m,c,a,p]   Save or restore time (modification, creation, access, preserve)
  88.  -u             Update files
  89.  -w<path>       Assign work directory
  90. #>
  91.  
  92. <#
  93. ===========================================================================================
  94. |                                                                                         |
  95. |                                        .NET Code                                        |
  96. |                                                                                         |
  97. ===========================================================================================
  98. #>
  99.  
  100. Add-Type -TypeDefinition @"
  101. using System;
  102. using System.Runtime.InteropServices;
  103.  
  104. public class Win32Functions {
  105.    [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
  106.    public static extern long StrFormatByteSizeW(long fileSize, System.Text.StringBuilder buffer, int bufferSize);
  107. }
  108. "@
  109.  
  110. <#
  111. ===========================================================================================
  112. |                                                                                         |
  113. |                                    Functions                                            |
  114. |                                                                                         |
  115. ===========================================================================================
  116. #>
  117. function Format-FileSize {
  118.    param(
  119.        [long]$fileSize
  120.    )
  121.    $buffer = New-Object System.Text.StringBuilder 260
  122.    [Win32Functions]::StrFormatByteSizeW($fileSize, $buffer, $buffer.Capacity) | Out-Null
  123.    return $buffer.ToString()
  124. }
  125.  
  126. function Show-WelcomeScreen {
  127.    Clear-Host
  128.    Write-Host ""
  129.    Write-Host " $($host.ui.RawUI.WindowTitle)"
  130.    Write-Host " +========================================================+"
  131.    Write-Host " |                                                        |"
  132.    Write-Host " | This script will use RAR.exe to compress each file in  |"
  133.    Write-Host " | the current working directory individually, each using |"
  134.    Write-Host " | different dictionary sizes, with max. compression,     |"
  135.    Write-Host " | generating this way multiple RAR files for evaluating  |"
  136.    Write-Host " | compression rates on these dictionary sizes.           |"
  137.    Write-Host " |                                                        |"
  138.    Write-Host " +=========================================================+"
  139.    Write-Host ""
  140.    Write-Host " Script Settings            " -ForegroundColor DarkGray
  141.    Write-Host " ===========================" -ForegroundColor DarkGray
  142.    Write-Host " RAR Executable Path: $([System.IO.Path]::GetFullPath($rarExecutablePath))" -ForegroundColor Gray
  143.    Write-Host "" -ForegroundColor DarkGray
  144.    Write-Host " Dictionary Sizes (Megabyte): $($dictionarySizesMb -join ', ')" -ForegroundColor Gray
  145.    Write-Host " The script will create a RAR archive for each specified dictionary size." -ForegroundColor DarkGray
  146.    Write-Host "" -ForegroundColor DarkGray
  147.    Write-Host " File Types To Keep Uncompressed: `$keepCompressedFileTypesUncompressed" -ForegroundColor Gray
  148.    Write-Host " The script will instruct RAR to don't compress the specified known compressed file types." -ForegroundColor DarkGray
  149.    Write-Host " (See `$keepCompressedFileTypesUncompressed variable definition to manage the file types)" -ForegroundColor DarkGray
  150.    Write-Host "" -ForegroundColor DarkGray
  151.    Write-Host " Tolerance File Size Difference: $(Format-FileSize -fileSize $toleranceSizeDiff)" -ForegroundColor Gray
  152.    Write-Host " Any newly created RAR file whose file size compared to previously   " -ForegroundColor DarkGray
  153.    Write-Host " created RAR files is within the specified tolerance value, it will be deleted." -ForegroundColor DarkGray
  154.    Write-Host " For example, if `$toleranceSizeDiff value is 1MB:" -ForegroundColor DarkGray
  155.    Write-Host " If a created RAR file of 32 MB dict. size has a file size of 100 MB," -ForegroundColor DarkGray
  156.    Write-Host " and then a newly created RAR file of 64 MB dict. size has a file size of 99 MB, " -ForegroundColor DarkGray
  157.    Write-Host " the RAR file of 64 MB dict. size will be deleted because it only differs in 1MB or less." -ForegroundColor DarkGray
  158.    Write-Host "" -ForegroundColor DarkGray
  159.    Write-Host " Keep only smallest RAR file: $keepOnlySmallestRarFile" -ForegroundColor Gray
  160.    Write-Host " If True, the script will delete any newly created RAR file " -ForegroundColor DarkGray
  161.    Write-Host " whose file size is bigger than previously created RAR files." -ForegroundColor DarkGray
  162.    Write-Host " Note: it takes into account the specified `$toleranceSizeDiff value." -ForegroundColor DarkGray
  163.    Write-Host "" -ForegroundColor DarkGray
  164.    Write-Host " Send RAR files to recycle bin: $sendRarFilesToRecycleBin" -ForegroundColor Gray
  165.    Write-Host " If True, the script will send RAR files to recycle bin instead of permanently deleting them." -ForegroundColor DarkGray
  166.    Write-Host ""
  167. }
  168.  
  169. function Confirm-Continue {
  170.    Write-Host " Press 'Y' key to continue or 'N' to exit."
  171.    Write-Host ""
  172.    Write-Host " -Continue? (Y/N)"
  173.    do {
  174.        $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  175.        $char = $key.Character.ToString().ToUpper()
  176.        if ($char -ne "Y" -and $char -ne "N") {
  177.            [console]::beep(1500, 500)
  178.        }
  179.    } while ($char -ne "Y" -and $char -ne "N")
  180.    if ($char -eq "N") {Exit(1)} else {Clear-Host}
  181. }
  182.  
  183. function Compress-Files {
  184.    Add-Type -AssemblyName Microsoft.VisualBasic
  185.  
  186.    $dictionarySizesMb = $dictionarySizesMb | Sort-Object
  187.  
  188.    # Partir y formatear la cadena de file types para acomodarlo a la linea de argumentos de rar.exe
  189.    if (-not [String]::IsNullOrEmpty($fileTypesToKeepUncompressed)) {
  190.        $fileTypeTokens = $fileTypesToKeepUncompressed -split ';'
  191.        $fileTypesArgumentLines = @()
  192.        for ($i = 0; $i -lt $fileTypeTokens.Count; $i += 20) {
  193.            $fileTypesArgumentLines += "-ms" + ($fileTypeTokens[$i..($i + 19)] -join ';') + [Environment]::NewLine
  194.        }
  195.        if ($fileTypesArgumentLines.Count -gt 0) {
  196.            $fileTypesArgumentLines[-1] = $fileTypesArgumentLines[-1] -replace [Environment]::NewLine, ''
  197.        }
  198.    } else {
  199.        $fileTypesArgumentLines = "-ms "
  200.    }
  201.  
  202.    foreach ($inputFile in Get-ChildItem -LiteralPath "$PSScriptRoot" -File) {
  203.  
  204.        if ($inputFile.Name -eq [System.IO.Path]::GetFileName($PSCommandPath)) {
  205.            continue
  206.        }
  207.  
  208.        # Keeps track of created rar files by rar.exe
  209.        $createdRarFiles = New-Object System.Collections.Generic.List[System.IO.FileInfo]
  210.  
  211.        foreach ($size in $dictionarySizesMb) {
  212.  
  213.            if (($size -ne $dictionarySizesMb[0]) -and ($inputFile.Length * 4) -le ($size * 1MB)) {
  214.                $formattedSize = Format-FileSize -fileSize $inputFile.Length
  215.                Write-Host "Ignoring compression with too big dictionary size of $size mb for a $formattedSize file: `"$($inputFile.Name)`"..." -ForegroundColor Yellow
  216.                continue
  217.            }
  218.  
  219.            $outputRarFilePath   = "$($inputFile.FullName)_$($size)mb.rar"
  220.            $errorLogFilePath = "$($inputFile.FullName)_$($size)mb_error.log"
  221.  
  222.            $arguments = @(
  223.                " a -u -ams -c- -cfg- -dh -ep1 -htb -idcdn -isnd- -iver -m5 -ma5 -md$($size)m",
  224.                " -o+ -oc -oh -oi2 -ol -oni -qo+ -r -ri0:0 -s- -t -tk -tl -tsmca+",
  225.                " $fileTypesArgumentLines",
  226.                " -x`"*\$($MyInvocation.MyCommand.Name)`"",
  227.                " -w`"$($env:TEMP)`"",
  228.                " -ilog`"$errorLogFilePath`"",
  229.                " -- `"$outputRarFilePath`"",
  230.                " -- `"$($inputFile.FullName)`""
  231.            )
  232.  
  233.            Write-Host "Compressing file with $size mb dictionary size: `"$($inputFile.Name)`"..."
  234.            #Write-Host ""
  235.            #Write-Host "rar.exe arguments:" -ForegroundColor DarkGray
  236.            #Write-Host ($arguments -join [Environment]::NewLine) -ForegroundColor DarkGray
  237.  
  238.            $previousForegroundColor = $host.UI.RawUI.ForegroundColor
  239.            $host.UI.RawUI.ForegroundColor = "DarkGray"
  240.            $psi = New-Object System.Diagnostics.ProcessStartInfo
  241.            $psi.FileName = $rarExecutablePath
  242.            $psi.Arguments = $arguments -join ' '
  243.            $psi.RedirectStandardOutput = $false
  244.            $psi.UseShellExecute = $false
  245.            $psi.CreateNoWindow = $false
  246.  
  247.            $process = [System.Diagnostics.Process]::Start($psi)
  248.            $process.WaitForExit()
  249.            $host.UI.RawUI.ForegroundColor = $previousForegroundColor
  250.  
  251.            $outputRarFile = New-Object System.IO.FileInfo($outputRarFilePath)
  252.            $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFile.Length
  253.            Write-Host ""
  254.            Write-Host "Created rar with file name: $($outputRarFile.Name) ($formattedOutputRarFileSize) ($($outputRarFile.Length) bytes)" -ForegroundColor DarkGreen
  255.  
  256.            if ($toleranceSizeDiff -ne $null) {
  257.                if ($createdRarFiles.Count -ne 0) {
  258.                    $outputRarFileSize = $outputRarFile.Length
  259.                    $formattedOutputRarFileSize = Format-FileSize -fileSize $outputRarFileSize
  260.                    $formattedToleranceFileSize = Format-FileSize -fileSize $toleranceSizeDiff
  261.  
  262.                    foreach ($createdRarFile in $createdRarFiles) {
  263.                        if ($createdRarFile.Exists) {
  264.                            $createdRarFileSize = $createdRarFile.Length
  265.                            $formattedCreatedRarFileSize = Format-FileSize -fileSize $createdRarFileSize
  266.                            $diffSize = [Math]::Abs($createdRarFileSize - $outputRarFileSize)
  267.                            $formattedDiffSize = Format-FileSize -fileSize $diffSize
  268.  
  269.                            if (($outputRarFileSize + $toleranceSizeDiff) -ge $createdRarFileSize) {
  270.                                Write-Host ""
  271.                                Write-Host "Size of this created RAR file ($formattedOutputRarFileSize) ($outputRarFileSize bytes) is within the $formattedToleranceFileSize tolerance difference" -ForegroundColor Yellow
  272.                                Write-Host "than a previously created RAR file of $formattedCreatedRarFileSize ($createdRarFileSize bytes) with smaller dictionary size..." -ForegroundColor Yellow
  273.                                Write-Host "Size of this created RAR file only differs by $formattedDiffSize ($diffSize bytes)." -ForegroundColor Yellow
  274.                                Write-Host "Deleting file: `"$($outputRarFile.Name)`"..." -ForegroundColor Yellow
  275.                                if ($sendRarFilesToRecycleBin) {
  276.                                    [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  277.                                } else {
  278.                                    [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($outputRarFile.FullName, 'OnlyErrorDialogs', 'DeletePermanently')
  279.                                }
  280.                                Write-Host "Deletion completed." -ForegroundColor Yellow
  281.                                break
  282.                            }
  283.                        }
  284.                    }
  285.                }
  286.            }
  287.  
  288.            if (Test-Path -LiteralPath $outputRarFile.FullName -PathType Leaf) {
  289.                $createdRarFiles.Add($outputRarFile)
  290.            }
  291.            Write-Host ""
  292.        }
  293.  
  294.        if ($keepOnlySmallestRarFile -and $createdRarFiles.Count -gt 0) {
  295.            $existingFiles = $createdRarFiles | Where-Object { $_.Exists }
  296.            if ($existingFiles.Count -gt 0) {
  297.                Write-Host "`$keepOnlySmallestRarFile variable is `$True. Comparing file sizes of created RAR files..." -ForegroundColor Yellow
  298.                Write-Host ""
  299.                $smallestFile = $existingFiles | Sort-Object Length | Select-Object -First 1
  300.                foreach ($file in $existingFiles) {
  301.                    if ($file -ne $smallestFile) {
  302.                        $formattedFileSize = Format-FileSize -fileSize $file.Length
  303.                        Write-Host "Deleting file: `"$($file.Name)`" ($formattedFileSize)..." -ForegroundColor Yellow
  304.                        if ($sendRarFilesToRecycleBin) {
  305.                            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'SendToRecycleBin')
  306.                        } else {
  307.                            [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($file.FullName, 'OnlyErrorDialogs', 'DeletePermanently')
  308.                        }
  309.                        Write-Host "Deletion completed." -ForegroundColor Yellow
  310.                        Write-Host ""
  311.                    }
  312.                }
  313.                $formattedSmallestFileSize = Format-FileSize -fileSize $smallestFile.Length
  314.                Write-Host "Smallest file kept: $($smallestFile.Name) ($formattedSmallestFileSize)" -ForegroundColor Green
  315.                Write-Host ""
  316.            }
  317.        }
  318.  
  319.    }
  320. }
  321.  
  322. function Show-GoodbyeScreen {
  323.    Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green
  324.    Write-Host ""
  325.    Write-Host "Press any key to exit..."
  326.    $key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
  327.    Exit(0)
  328. }
  329.  
  330. <#
  331. ===========================================================================================
  332. |                                                                                         |
  333. |                                         Main                                            |
  334. |                                                                                         |
  335. ===========================================================================================
  336. #>
  337.  
  338. [System.Console]::Title = "RAR Multi-Compression Test Tool (Files) - by Elektro"
  339. #[System.Console]::SetWindowSize(150, 45)
  340. [CultureInfo]::CurrentUICulture = "en-US"
  341.  
  342. try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
  343.  
  344. Show-WelcomeScreen
  345. Confirm-Continue
  346. Compress-Files
  347. Show-GoodbyeScreen
  348.  
55  Foros Generales / Sugerencias y dudas sobre el Foro / [SOLUCIONADO] He publicado catorce hilos en el lugar incorrecto y de forma absurda... en: 19 Marzo 2024, 01:09 am
Hola.

En la sección de programación general (https://foro.elhacker.net/programacion_general-b18.0/), en la primera página, publiqué varios hilos cuyos títulos empiezan con el prefijo "[APORTE]".

Pues todos esos hilos en realidad deberían ir en la sección de scripting.

Me he dado cuenta ahora, o mejor dicho he caído ahora en la cuenta de que estaban publicados en otra sección del foro, por que he publicado un nuevo aporte en la sección de scripting y no encontraba estos otros hilos ahí, y me ha extrañado, y pensé para mis adentros: "¿dónde coño están mis otros hilos, me los habrán borrado sin decir nada?" :xD.

El caso es que los publiqué en la sección de Programación General de forma inconsciente, no seguí ningún criterio en especial, simplemente fue un acto inconsciente publicarlos ahí en Programación General, pero en realidad todos esos aportes son de lenguajes de scripting, así que... no están en su sección adecuada.

Y es un poco absurdo, por que frecuentemente accedo a la sección de Programación General y veo mis hilos en la primera página de esa sección, y en todos los catorce hilos se puede ver perfectamente como comienzo el texto con frases similares a: "El siguiente script sirve para realizar tal cosa...", pero nada, que no he caído en la cuenta de que estaban publicados en la sección incorrecta, hasta ahora xD. Algo totalmente inconsciente por mi parte como ya digo.

Son 14 hilos. Puede resultar tedioso moverlos (ya no me acuerdo cómo de fácil o tedioso era), pero bueno, un error inconsciente lo podemos tener cualquiera, disculpen.

PD: Si alguien se había fijado en ello, quiero decir, que ese no era el lugar más indicado para ese tipo de aportes, ¡debería haberme dicho algo! (que no soy tan cascarrabias como algunos se pensarán).

Un saludo.
56  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
Código
  1. ' Mount VMWare Shared Folders Network Drive
  2.  
  3. Option Explicit
  4.  
  5. Dim objFSO, objShell, objNetwork, colDrives, colNetDrives, i, msg
  6. Dim objDrive, vmWareDrive, vmWarePath, drive, path
  7.  
  8. vmWareDrive = "Z:"
  9. vmWarePath  = "\\vmware-host\Shared Folders"
  10.  
  11. Set objFSO = CreateObject("Scripting.FileSystemObject")
  12. Set objShell = CreateObject("WScript.Shell")
  13. Set objNetwork = CreateObject("WScript.Network")
  14. Set colDrives = objFSO.Drives
  15. Set colNetDrives = objNetwork.EnumNetworkDrives
  16.  
  17. For i = 0 to colNetDrives.Count - 1 Step 2
  18. drive = colNetDrives.Item(i)
  19. path  = colNetDrives.Item(i+1)
  20.  
  21. If (LCase(drive) = LCase(vmWareDrive)) Then
  22. If (LCase(path) = LCase(vmWarePath)) Then
  23. msg = "A network drive is already mounted with same letter and UNC path:" & vbCrLf & vbCrLf
  24. msg = msg & drive & vbTab & """" & path & """"
  25. objShell.Popup msg, 20, "Warning: Network Drives", 48
  26. Else
  27. msg = "A network drive is already mounted with a different UNC path:" & vbCrLf & vbCrLf
  28. msg = msg & drive & vbTab & """" & path & """"
  29. objShell.Popup msg, 20, "Error: Network Drives", 16
  30. End If
  31. WScript.Quit()
  32. End If
  33. Next
  34.  
  35. For Each objDrive in colDrives
  36. drive = objDrive.DriveLetter & ":"
  37. If (LCase(drive) = LCase(vmWareDrive)) Then
  38. msg = "A local drive is already mounted with the same drive letter:" & vbCrLf & vbCrLf
  39. msg = msg & "Letter: " & drive & vbCrLf
  40. msg = msg & "FileSystem: " & objDrive.FileSystem & vbCrLf
  41. msg = msg & "Volume Name: " & objDrive.VolumeName & vbCrLf
  42. msg = msg & "Share Name: " & objDrive.ShareName
  43. objShell.Popup msg, 20, "Error: Network Drives", 16
  44. WScript.Quit()
  45. End If
  46. Next
  47.  
  48. objNetwork.MapNetworkDrive vmWareDrive, vmWarePath
  49.  
  50. msg = "The following network drive was successfully mounted:" & vbCrLf & vbCrLf
  51. msg = msg & vmWareDrive & vbTab & """" & vmWarePath & """"
  52. objShell.Popup msg, 20, "Info: Network Drives", 64
  53. WScript.Quit()



Unmount Shared Folders Network Drive.vbs
Código
  1. ' Unmount VMWare Shared Folders Network Drive
  2.  
  3. Option Explicit
  4.  
  5. Dim objShell, objNetwork, colDrives, i, msg
  6. Dim vmWareDrive, vmWarePath, drive, path
  7.  
  8. vmWareDrive = "Z:"
  9. vmWarePath  = "\\vmware-host\Shared Folders"
  10.  
  11. Set objShell = CreateObject("WScript.Shell")
  12. Set objNetwork = CreateObject("WScript.Network")
  13. Set colDrives = objNetwork.EnumNetworkDrives
  14.  
  15. For i = 0 to colDrives.Count - 1 Step 2
  16. drive = colDrives.Item(i)
  17. path  = colDrives.Item(i+1)
  18.  
  19. If (LCase(drive) = LCase(vmWareDrive)) Then
  20. If (LCase(path) = LCase(vmWarePath)) Then
  21. objNetwork.RemoveNetworkDrive vmWareDrive, True, True
  22.  
  23. msg = "The following network drive was successfully unmounted:" & vbCrLf & vbCrLf
  24. msg = msg & drive & vbTab & """" & path & """"
  25. objShell.Popup msg, 20, "Info: Network Drives", 64
  26. Else
  27. msg = "A network drive is already mounted with a different UNC path:" & vbCrLf & vbCrLf
  28. msg = msg & drive & vbTab & """" & path & """"
  29. objShell.Popup msg, 20, "Warning: Network Drives", 16
  30. End If
  31. WScript.Quit()
  32. End If
  33. Next
  34.  
  35. msg = "No matching network drive " & """" & vmWareDrive & """" & " was found."
  36. objShell.Popup msg, 20, "Error: Network Drives", 16
  37. WScript.Quit()
57  Programación / Scripting / Re: Archivo bat para borrar una entrada de registro en: 18 Marzo 2024, 21:50 pm
Hola, muchas gracias, acabo de probarlo y esto es el resultado:

https://ibb.co/4NRRP2h

Te sugiero que vuelvas a probar el script, pero esta vez ejecútalo desde la cuenta integrada "Administrador" en Windows.

Para activar la cuenta integrada "Administrador", y asumiendo que tengas suficientes permisos de usuario para ello, simplemente abre la CMD y escribe el siguiente comando:

Código:
net user administrador /active:yes
- https://petri.com/how-to-enable-built-in-administrator-account-windows-10/

Una vez que la cuenta integrada "Administrador" esté activa, simplemente inicia sesión en dicha cuenta de usuario, y ejecuta el script de PowerShell para que el script vuelva a intentar realizar las modificaciones de permisos de usuario sobre las claves de la rama HKLM.



En caso de que la metodología de adquisición de permisos sobre las claves del registro de la rama HKLM mediante PowerShell te siga fallando, en ese caso te sugiero, desde la cuenta "Administrador", seguir las siguientes indicaciones:

1. Descarga del siguiente enlace el programa de terceros por línea de comandos 'SetACL' (no confundir con 'SetACL Studio'):

2. Coloca el archivo executable descargado, "setacl.exe", junto a este batch-script en la misma carpeta:

SetAcl.cmd
Código
  1. @ECHO OFF
  2.  
  3. Set "RegKey=HKEY_LOCAL_MACHINE\SOFTWARE\Classes\PackagedCom\Package"
  4.  
  5. ".\SETACL.exe" -on "%RegKey%" -ot "reg" ^
  6.               -actn "setowner" -ownr "n:%UserName%" -rec "Yes" ^
  7.               -actn "ace" -ace "n:%UserName%;p:full;m:Grant" -rec "Yes"
  8.  

3. Ejecuta el script. Deberías ver algo como esto:



En caso de que te de error indicando que no se ha podido realizar correctamente la operación en el registro, modifica el valor de esta variable:

Código:
Set "RegKey=HKEY_LOCAL_MACHINE\SOFTWARE\Classes\PackagedCom\Package"

Por este otro valor:
Código:
Set "RegKey=HKEY_LOCAL_MACHINE\SOFTWARE\Classes\PackagedCom"

Y vuelve a ejecutar el script.

En caso de que te siga dando error, sigue acortando el valor, y volviendo a ejecutar el script con la clave de registro acortada, hasta llegar a la raíz HKLM:

Código:
Set "RegKey=HKEY_LOCAL_MACHINE\SOFTWARE\Classes"
Código:
Set "RegKey=HKEY_LOCAL_MACHINE\SOFTWARE"
Código:
Set "RegKey=HKEY_LOCAL_MACHINE"

La idea es modificar el propietario y obtener permisos completos de las claves de registro donde sea estrictamente necesario obtenerlos, preferiblemente NO en la rama HKLM al completo, por eso te he indicado que vayas acortando el valor (la ruta del registro) poco a poco mientras vas ejecutando el batch-script por cada cambio que hagas.

Con estas indicaciones, desde el punto nº1 al nº3, se asume que entiendes los posibles riesgos que puede conllevar modificar los permisos de usuario de las claves del registro de Windows. No me hago responsable de un posible malfuncionamiento en el sistema operativo tras aplicar cambios de permisos de usuario en el registro de Windows.

Aténtamente,
Elektro.
58  Programación / Scripting / Re: Archivo bat para borrar una entrada de registro en: 18 Marzo 2024, 08:02 am
El error se debe a que no tienes permisos de eliminación sobe la clave.

Prueba con esta nueva modificación:



Código
  1. <# REGISTRY KEY DEFINITIONS #>
  2.  
  3. $RegKeys = @(
  4.    @{Path = "HKCR\*\shell\ShareWithSkype"
  5.      IsLiteralPath = $true},
  6.    @{Path = "HKCR\PackagedCom\ClassIndex\{776DBC8D-7347-478C-8D71-791E12EF49D8}"
  7.      IsLiteralPath = $true},
  8.    @{Path = "HKCR\SOFTWARE\Classes\PackagedCom\Package\Microsoft.SkypeApp*\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8}"
  9.      IsLiteralPath = $false},
  10.    @{Path = "HKLM\SOFTWARE\Classes\PackagedCom\Package\Microsoft.SkypeApp*\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8}"
  11.      IsLiteralPath = $false}
  12. )
  13.  
  14. <# https://stackoverflow.com/a/35843420/1248295 #>
  15.  
  16. function Take-Permissions {
  17.    # Developed for PowerShell v4.0
  18.    # Required Admin privileges
  19.    # Links:
  20.    #   http://shrekpoint.blogspot.ru/2012/08/taking-ownership-of-dcom-registry.html
  21.    #   http://www.remkoweijnen.nl/blog/2012/01/16/take-ownership-of-a-registry-key-in-powershell/
  22.    #   https://powertoe.wordpress.com/2010/08/28/controlling-registry-acl-permissions-with-powershell/
  23.  
  24.    param($rootKey, $key, [System.Security.Principal.SecurityIdentifier]$sid = 'S-1-5-32-545', $recurse = $true)
  25.  
  26.    switch -regex ($rootKey) {
  27.        'HKCU|HKEY_CURRENT_USER'    { $rootKey = 'CurrentUser' }
  28.        'HKLM|HKEY_LOCAL_MACHINE'   { $rootKey = 'LocalMachine' }
  29.        'HKCR|HKEY_CLASSES_ROOT'    { $rootKey = 'ClassesRoot' }
  30.        'HKCC|HKEY_CURRENT_CONFIG'  { $rootKey = 'CurrentConfig' }
  31.        'HKU|HKEY_USERS'            { $rootKey = 'Users' }
  32.    }
  33.  
  34.    ### Step 1 - escalate current process's privilege
  35.    # get SeTakeOwnership, SeBackup and SeRestore privileges before executes next lines, script needs Admin privilege
  36.    $import = '[DllImport("ntdll.dll")] public static extern int RtlAdjustPrivilege(ulong a, bool b, bool c, ref bool d);'
  37.    $ntdll = Add-Type -Member $import -Name NtDll -PassThru
  38.    $privileges = @{ SeTakeOwnership = 9; SeBackup =  17; SeRestore = 18 }
  39.    foreach ($i in $privileges.Values) {
  40.        $null = $ntdll::RtlAdjustPrivilege($i, 1, 0, [ref]0)
  41.    }
  42.  
  43.    function Take-KeyPermissions {
  44.        param($rootKey, $key, $sid, $recurse, $recurseLevel = 0)
  45.  
  46.        ### Step 2 - get ownerships of key - it works only for current key
  47.        $regKey = [Microsoft.Win32.Registry]::$rootKey.OpenSubKey($key, 'ReadWriteSubTree', 'TakeOwnership')
  48.        $acl = New-Object System.Security.AccessControl.RegistrySecurity
  49.        $acl.SetOwner($sid)
  50.        $regKey.SetAccessControl($acl)
  51.  
  52.        ### Step 3 - enable inheritance of permissions (not ownership) for current key from parent
  53.        $acl.SetAccessRuleProtection($false, $false)
  54.        $regKey.SetAccessControl($acl)
  55.  
  56.        ### Step 4 - only for top-level key, change permissions for current key and propagate it for subkeys
  57.        # to enable propagations for subkeys, it needs to execute Steps 2-3 for each subkey (Step 5)
  58.        if ($recurseLevel -eq 0) {
  59.            $regKey = $regKey.OpenSubKey('', 'ReadWriteSubTree', 'ChangePermissions')
  60.            $rule = New-Object System.Security.AccessControl.RegistryAccessRule($sid, 'FullControl', 'ContainerInherit', 'None', 'Allow')
  61.            $acl.ResetAccessRule($rule)
  62.            $regKey.SetAccessControl($acl)
  63.        }
  64.  
  65.        ### Step 5 - recursively repeat steps 2-5 for subkeys
  66.        if ($recurse) {
  67.            foreach($subKey in $regKey.OpenSubKey('').GetSubKeyNames()) {
  68.                Take-KeyPermissions $rootKey ($key+'\'+$subKey) $sid $recurse ($recurseLevel+1)
  69.            }
  70.        }
  71.    }
  72.  
  73.    Take-KeyPermissions $rootKey $key $sid $recurse
  74. }
  75.  
  76. <# REGISTRY KEYS DELETION #>
  77.  
  78. $currentIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
  79. $sid = $currentIdentity.User.Translate([System.Security.Principal.SecurityIdentifier])
  80.  
  81. foreach ($regKey in $RegKeys) {
  82.    [String]$path = $regKey.Path
  83.    [String]$root = $path -replace '^(.*?)\\.*', '$1'
  84.    [String]$key = $path -replace "$root\\", ""
  85.    [Boolean]$isLiteralPath = $regKey.IsLiteralPath
  86.  
  87.    if (-not $isLiteralPath) {
  88.        $key = $key.Substring(0, $key.LastIndexOf('*'))
  89.        $key = $key.Substring(0, $key.LastIndexOf('\'))
  90.    }
  91.  
  92.    Write-Host "Taking registry permissions for: $root\$key"
  93.    try { Take-Permissions $root $key $sid $true } catch { }
  94.  
  95.    [Boolean]$testPath = if ($isLiteralPath) { Test-Path -LiteralPath "Registry::$path" } else { Test-Path "Registry::$path" }
  96.    if ($testPath) {
  97.        try {
  98.            if ($isLiteralPath) {
  99.                Remove-Item -LiteralPath "Registry::$path" -Recurse -ErrorAction Stop
  100.            } else {
  101.                Remove-Item -Path "Registry::$path" -Recurse -ErrorAction Stop
  102.            }
  103.            Write-Host "Registry key deleted: $path"
  104.        } catch {
  105.            Write-Error $_.Exception.Message
  106.        }
  107.    } else {
  108.        Write-Warning "Registry key not found: $path"
  109.    }
  110.    Write-Host ""
  111. }
  112.  
  113. <# END #>
  114.  
  115. Write-Host "Operation Completed.`n"-BackgroundColor Black -ForegroundColor Green
  116. Write-Host "Press any key to exit..."
  117. $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") | Out-Nu
  118. Exit(0)
59  Programación / Scripting / Re: Archivo bat para borrar una entrada de registro en: 18 Marzo 2024, 03:15 am
Esto es lo que debería borrar en el registro:

https://www.dropbox.com/scl/fi/ozju0sdo40bcfam5f14ge/04.jpg

Y esa es precisamente la clave que encuentra y termina borrando, como expliqué en mi primer comentario.



Podría haber algún problema de permisos de usuario; el script que has mostrado igora los errores sin mostrar información en caso de error (bloque catch vacío).

Lo he modificado un poco (bastante) a conveniencia para informar sobre errores. Asegúrate de que las rutas del registro son correctas por que no se si las he escrito bien viendo las capturas de pantalla:



Script.ps1
Código
  1. <# REGISTRY KEY DEFINITIONS #>
  2.  
  3. $RegKeys = @(
  4. @{Path = "HKCR\*\shell\ShareWithSkype"
  5.  IsLiteralPath = $true},
  6. @{Path = "HKCR\PackagedCom\ClassIndex\{776DBC8D-7347-478C-8D71-791E12EF49D8}"
  7.  IsLiteralPath = $true},
  8. @{Path = "HKCR\SOFTWARE\Classes\PackagedCom\Package\Microsoft.SkypeApp*\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8}"
  9.  IsLiteralPath = $false},
  10. @{Path = "HKLM\SOFTWARE\Classes\PackagedCom\Package\Microsoft.SkypeApp*\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8}"
  11.  IsLiteralPath = $false}
  12. )
  13.  
  14. <# REGISTRY KEYS DELETION #>
  15.  
  16. foreach ($regKey in $RegKeys) {
  17. [String]$path = $regKey.Path
  18. [Boolean]$testPath = if ($regKey.IsLiteralPath) { Test-Path -LiteralPath "Registry::$path" } else { Test-Path "Registry::$path" }
  19.  
  20. if ($testPath) {
  21. try {
  22. Remove-Item -Path "Registry::$path" -Recurse -ErrorAction Stop
  23. Write-Host "Registry key deleted: $path"
  24. } catch {
  25. Write-Error $_.Exception.Message
  26. }
  27. } else {
  28. Write-Warning "Registry key not found: $path"
  29. }
  30. }
  31.  
  32. <# END #>
  33.  
  34. Write-Host "`nOperation Completed.`n"-BackgroundColor Black -ForegroundColor Green
  35. Write-Host "Press any key to exit..."
  36. $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") | Out-Nu
  37. Exit(0)
60  Programación / Scripting / Re: Archivo bat para borrar una entrada de registro en: 17 Marzo 2024, 23:12 pm

Lamentablemente no puedo ver ninguna de las imágenes que has compartido, ya que se requiere aceptar una solicitud de acceso por tu parte:

Citar
No tienes acceso a este contenido. Has iniciado sesión como ****@****.com.

Acepta mi solicitud (por cada archivo que has subido) o prueba a subir las imágenes en algún hosting de imágenes como https://imgur.com/.
Páginas: 1 2 3 4 5 [6] 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines