使用 Invoke-Expression 初始化变量
我正在尝试使用 Invoke-Expression 来初始化 powershell 脚本中的多个变量。
这是变量:
$saved_state_file = './var/mirmon.tmp';
$log_file = './var/mirmon.log';
$once_file = './var/once';
$plugin_dir = './libexec';
$verbose = 0;
$pause = 0;
$submit_method = 'ssh,http,smtp';
$http_user = $null
$http_pass = $null
这是函数:
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
}
这是我正在尝试阅读的示例:
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
但是调用表达式的范围似乎存在一些问题,因为这些值是在 read_config 函数中设置的,但是当运行结束后,值将返回到其原始值。
谁能告诉我问题是什么?
吉斯利
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_file = './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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想你已经很清楚了。这是一个范围问题。当您构建 $exp 时,请将 $Script: 放在每个变量名称前面(因此 $Script:Verbose=2 而不是 $verbose=2)。这将强制变量的范围为脚本级别。
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.