2012-02-04 137 views
0

我有以下功能:功能运行

function CheckNagiosConfig { 

# Query nConf for hosts 
Invoke-Expression -command $nconf_command_host | Out-file $nconf_export_host_file 
$nconf_export_host = Import-Csv $nconf_export_host_file -Delimiter ";" 

# Query nConf for services 
Invoke-Expression -command $nconf_command_service | Out-file $nconf_export_service_file 
$nconf_export_service = Import-Csv $nconf_export_service_file -Delimiter ";" 

return $nconf_export_host 
return $nconf_export_service 
} 

,但是当我把这个与CheckNagiosConfig没有正在运行...我缺少什么? 而且,我是否正确返回变量?这是做到这一点的方式吗?

回答

1

首先你的函数在第一次返回时结束(返回$ nconf_export_host),第二次是从未见过。如果你想返回多个元素(一个数组),你应该使用Write-Output CmdLet。


编辑

回访瓦尔你有至少三种解决方案:

1)通过书面方式

$global:nconf_export_host = Import-Csv $nconf_export_host_file -Delimiter ";" 

与一个全局变量范围工作
$script:nconf_export_host = Import-Csv $nconf_export_host_file -Delimiter ";" 

您可以在功能外使用$nconf_export_host

2)传输参数参照

function CheckNagiosConfig ([ref]$nconf_export_host, [ref]$$nconf_export_service) 
{ 
    ... 
    $nconf_export_host.value = Import-Csv $nconf_export_host_file -Delimiter ";" 

    ... 
    $nconf_export_service.value = Import-Csv $nconf_export_service_file -Delimiter ";" 

    return $true 
} 

的功能在这种情况下,你可以保持语义返回值的指定函数是如何工作的,你可以在函数内部修改的参数传递引用。

3)使用输出本身

function CheckNagiosConfig { 

# Query nConf for hosts 
Invoke-Expression -command $nconf_command_host | Out-file $nconf_export_host_file 
$nconf_export_host = Import-Csv $nconf_export_host_file -Delimiter ";" 
write-output $nconf_export_host 

# Query nConf for services 
Invoke-Expression -command $nconf_command_service | Out-file $nconf_export_service_file 
$nconf_export_service = Import-Csv $nconf_export_service_file -Delimiter ";" 

return $nconf_export_service 
} 

使用:

$a = CheckNagiosConfig 
# $a[0] will be $nconf_export_host 
# $a[1] will be $nconf_export_service 
+0

感谢您在清除了!但是,如何返回从函数创建的变量呢? – Sune 2012-02-04 22:19:57

+0

我编辑了我的答案,向你解释了多种返回变量的方法。 – JPBlanc 2012-02-05 12:53:19

+0

非常感谢你! – Sune 2012-02-07 09:40:22