Reputation: 53
I've written a menu which will feed an integer into the selectPod function and then I want the $sqlSettings object populated with Server and database to use in a few SQL Queries I've written later in the script. I've done the tricky bits but can't seem to get this working.
$SQLServer = @()
$Server = @()
$database = @()
function selectPod($podnumber) {
switch ($podnumber)
{
1 { $Server = "SQLSERVER01";
$Database = "DATABASE01"
}
2 { $Server = "SQLSERVER02";
$Database = "DATABASE02"
}
3 { $Server = "SQLSERVER03";
$Database = "DATABASE03"}
4 { $Server = "SQLSERVER04";
$Database = "DATABASE04"}
5 { $Server = "SQLSERVER05"
$Database = "DATABASE05"}
}
$properties = $params = @{
'Pod' = $podnumber;
'SQLServer' = $Server;
'Database' = $Database;
}
$sqlSettings = New-Object -TypeName PSObject -Property $properties
Write-Output $sqlSettings
}
selectPod 5
Write-Host "you are targeting " $($SQLSettings.POD) " which is SQLServer`
$($SQLSettings.server) and $($SQLSettings.database)" -ForegroundColor Green
I know it's working becuase the write output is fine. But the write-host show's it's not surviving outside the function.
you are targeting which is SQLServer and
SQLServer Pod Database
--------- --- --------
SQLSERVER05 5 DATABASE05
I'm probably doing this completely the wrong way but any assistance would be appreciated.
Upvotes: 1
Views: 188
Reputation: 1128
Move your Write-Host command into the switch block. If you want to use the output object for anything else, collect it in a variable like this:
$sqlSettings = selectpod 5
Upvotes: 0
Reputation: 3923
Variables within a function are confined to the function unless you declare otherwise. Either assign a script/global variable to the result e.g. $Global:SQLSettings - or a better way is to return your value from the function as an object.
Replace Write-Output $sqlSettings
With Return $sqlSettings
...and look at the value returned when you run the function e.g.
$Result = selectPod 5
Upvotes: 3