Sune
Sune

Reputation: 3270

Function not being run

I have the following function:

 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
}

but when I call this with CheckNagiosConfig nothing is being run.. What am I missing? And, am I returning the variables correctly? Is this the way to do it?

Upvotes: 0

Views: 102

Answers (1)

JPBlanc
JPBlanc

Reputation: 72612

First your function ends on first return (return $nconf_export_host), the second one is never seen. If you want to return mutliple things (an array) you shoud use Write-Output CmdLet.


Edited

For returning vars you've got at least three solutions :

1) Working on the scope with a global var by writting

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

or

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

You can use $nconf_export_host outside the function.

2) Passing arguments to function by reference

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
}

In this case, you can keep the semantic of the returned value to specify how the function works, and you can modify inside the function, the arguments passed by reference.

3) Using the output itself

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
}

used with :

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

Upvotes: 1

Related Questions