2012-02-04 120 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