如何在Perl中设置Win32系统环境变量?

时间:2010-10-01 06:39:49

标签: windows perl environment-variables

我希望能够在Perl中设置系统环境变量,并编写了以下脚本(灵感来自this idea)来完成此任务:

use Win32;
use Win32::API;
use Win32::OLE qw( in );

my $machine = ".";
my $WMIServices = Win32::OLE->GetObject ( "winmgmts:{impersonationLevel=impersonate,(security)}//$machine/root/cimv2" ) || die;

my $objVariable = $WMIServices->Get("Win32_Environment")->SpawnInstance_;
$objVariable->{Name}="NewOSType";
$objVariable->{UserName} = "<System>";
$objVariable->{VariableValue} = "LAMBDA";
$objVariable->Put_;

但是,我不是Perl的专家,我想知道专家对此代码的看法。这是实现这一目标的最佳方式吗?

1 个答案:

答案 0 :(得分:4)

另一种可能的方法:

use strict;
use warnings;
use Win32::TieRegistry qw[:KEY_];
use Win32::API;
use constant HWND_BROADCAST => -1;
use constant WM_SETTINGCHANGE => 0x1a;

my $hklm_env = Win32::TieRegistry->new(
    'HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Control/Session Manager/Environment', 
    { Access => KEY_READ() | KEY_WRITE(), Delimiter => '/' }
); # returns undef if SYSTEM ENV not writable

my $hkcu_env = Win32::TieRegistry->new(
    'HKEY_CURRENT_USER/Environment', 
    { Access => KEY_READ() | KEY_WRITE(), Delimiter => '/' }
);

# if SYSTEM ENV not writable try USER ENV
my $e = defined($hklm_env) ? $hklm_env : $hkcu_env;

if(defined $e) {
  $e->SetValue('Variable', 'Value');  
}
else {
  warn "Cannot open neither SYSTEM ENV nor USER ENV registry for Read+Write";
}

my $SendMessage = new Win32::API("user32", "SendMessage", 'NNNP', 'N') or die "Couldn't create SendMessage: $!\n";
my $RetVal = $SendMessage->Call(HWND_BROADCAST,WM_SETTINGCHANGE,0,'Environment');