开发者

Initialize variables with Invoke-Expression

开发者 https://www.devze.com 2023-03-27 06:14 出处:网络
I\'m trying to use Invoke-Expression to initialize a number of variables in my powershell script. Here are the variables:

I'm trying to use Invoke-Expression to initialize a number of variables in my powershell script.

Here are the variables:

$saved_state_file = './var/mirmon.tmp';
$log_file = './var/mirmon.log';
$once_fi开发者_开发技巧le = './var/once';
$plugin_dir = './libexec';
$verbose = 0;
$pause = 0;
$submit_method = 'ssh,http,smtp';
$http_user = $null
$http_pass = $null

Here is the function:

function read_config{
     $lasthost = 'Default'
     $return = @()
     $checks = @()
     $logs = @()
     foreach ($s in Get-Content $config_file){
         if(){...}
         else{
             $split = $s.Split('=',$option)
             $exp = "$" + $split[0] + '=' + '"' + $split[1] + '"'
             Invoke-Expression $exp
             }
      }
$return = $checks,$logs
return $return

}

And here is an example of what I´m trying to read:

verbose=2
http_user = user
http_pass = passw
smtp_host = test.some.com
log_file=/tmp/test.log
saved_state_file=/tmp/test.test.tmp
hung_time=20
plugin_dir=libexec
once_file=/tmp/once
submit_method=http

But there seems to be some problem with the scope of invoke-expression because the values are set in the read_config function but when that has finished running the values go back to their original values.

Can anyone tell me what the problem is?

Gísli


I think you pretty much figured it out. It is a scope issue. When you are building your $exp, put $Script: in front of each variable name (so $Script:Verbose=2 instead of $verbose=2). That will force the scope for the variable to the script level.

0

精彩评论

暂无评论...
验证码 换一张
取 消