使用 Perl 删除整个 Reg 目录

Delete a Entire Reg Directory using Perl

我想使用 perl 命令删除 Windows 机器中的注册表。 我怎样才能做到这一点 。我尝试了一些来自互联网的命令,它正在执行但没有被删除 请提供帮助!! 下面的代码执行,但不删除 Reg Key

use warnings;
use strict;

use Win32::TieRegistry( Delimiter=>"/", ArrayValues=>0 );

my $myway= delete $Registry->{"HKEY_LOCAL_MACHINE/SOFTWARE/Keypath"};

print "Done";

首先您需要删除注册表项的正确权限(尝试 运行 来自具有管理员权限的 CMD 的 Perl 脚本),其次根据 documentation 您只能删除提供的项它不包含任何子项:

You can use the Perl delete function to delete a value from a Registry key or to delete a subkey as long that subkey contains no subkeys of its own.

第三,即使您 运行 拥有管理员权限,仍然有一些密钥是您无法删除的,请参阅 this 问答了解更多信息。

所以如果你想删除整个子树,你需要自下而上遍历树并分别删除每个子键。这是一个例子:

use feature qw(say);
use warnings;
use strict;
use Data::Dumper qw(Dumper);
use Win32::RunAsAdmin qw(force);
use Win32API::Registry qw(regLastError KEY_READ KEY_WRITE);
use Win32::TieRegistry( Delimiter=>"/", ArrayValues=>0 );
{
    # Choose the top root node that should be deleted
    # Note: This and all its subkeys will be deleted from the registry.
    # Note: Will only succeed if you have permission to write to each sub key
    my $top_key_name = "HKEY_CLASSES_ROOT/Directory/Background/shell/Foo";
    my $tree = $Registry->Open(
        $top_key_name,  
       { Access=>KEY_READ()|KEY_WRITE(), Delimiter=>"/" } 
    );
    die "Could not open key $top_key_name: $^E" if !defined $tree;
    delete_subtree( $tree, my $level = 0);
}

sub delete_subtree {
    my ($tree, $level) = @_;
    my $path = $tree->Path();
    my @subkeys = $tree->SubKeyNames();
    for my $name (@subkeys) {
        my $subtree = $tree->{$name."/"};
        if (!defined $subtree) {
            die "Cannot access subkey $name for $path: " . regLastError() . ". Abort.";
        }
        if (ref $subtree) {
            delete_subtree($subtree, $level + 1);
        }
        else {
            die "Subkey $name for $path is not a hash ref. Abort.";
        }
    }
    
    # assuming the previous recursive code has deleted all sub keys of the 
    # current key, we can now try delete this key
    say "Trying to delete $path ..";
    my $res = delete $Registry->{$path};
    if (!defined $res) {
        die "..Failed to delete key : $^E";
    }
    else {
        say "  -> success";
    }
}