Hi Team,
I am trying to access SQL Database tables where the IP address/Hostname, User ID and password information are stored.
This is how it is setup:
- I have created custom tables in SQL with IP address as navchar datatype, user ID as navchar datatype and password as navchar datatype
- I have inserted data into the columns, added the IP address, user ID as domainname\username and password in plain text
- With the below script, I am unable to connect to SQL Database and query the table to get the output individually
But when I try to assign the values from SQL table to variables and try to connect to the vCenter, I get an error as to the host is not resolvable. But I can use same information and connect with a different session.
I am using the below script, where Get-MOLDatabaseData function connects to SQL Server.
Can someone please look into the script and let me know if there is anything missing?
# load the VMware module
$VimAutoCore = "VMware.VimAutomation.Core"
if ( (Get-PSSnapin -Name $VimAutoCore -ErrorAction SilentlyContinue) -eq $null ) {
Write-Host "loading $VimAutoCore powershell module"
Add-PsSnapin $VimAutoCore
}
function Get-MOLDatabaseData {
[CmdletBinding()]
param (
[string]$connectionString,
[string]$query,
[switch]$isSQLServer
)
if ($isSQLServer) {
Write-Verbose 'in SQL Server mode'
$connection = New-Object -TypeName `
System.Data.SqlClient.SqlConnection
} else {
Write-Verbose 'in OleDB mode'
$connection = New-Object -TypeName `
System.Data.OleDb.OleDbConnection
}
$connection.ConnectionString = $connectionString
$command = $connection.CreateCommand()
$command.CommandText = $query
if ($isSQLServer) {
$adapter = New-Object -TypeName `
System.Data.SqlClient.SqlDataAdapter $command
} else {
$adapter = New-Object -TypeName `
System.Data.OleDb.OleDbDataAdapter $command
}
$dataset = New-Object -TypeName System.Data.DataSet
$adapter.Fill($dataset) | Out-Null
$dataset.Tables[0]
$connection.close()
}
#This variable connects to SQL Server Database
$SQLConnectionString = "Server=hostname;Database=dbname;User Id=sa;Password=password;"
#Variable to retrieve vCenter IP, Username and password
$vCenterIP = Get-MOLDatabaseData -connectionString $SQLConnectionString -isSQLServer -query "SELECT vCenterIP FROM server_table"
$vCenterUser = Get-MOLDatabaseData -connectionString $SQLConnectionString -isSQLServer -query "SELECT UserID FROM server_table"
$vCenterPassword = Get-MOLDatabaseData -connectionString $SQLConnectionString -isSQLServer -query "SELECT Password FROM server_table"
#Connect to vCenter Server
Connect-VIServer -Server $vCenterIP -User $vCenterUser -Password $vCenterPassword -ErrorAction Stop