0

I am having an issue where I need to run a query (Fetch an IP address) against my MySql database and put the result into a variable (for use when cloning a VM) However, this doesn't seem to work as the Variable turns up empty. The 'NewVMIP' variable should end up containing the IP from the MySQL database. There are no errors when accessing the database and selecting the information, the issue seems to lie when trying to use the variable when cloning the VM, it is just blank.

# SELECT IP FROM DB #

[void][system.reflection.Assembly]::LoadFrom("C:\Program Files (x86)\MySQL\Connector.NET 6.9\Assemblies\v2.0\MySQL.Data.dll")
$myconnection = New-Object MySql.Data.MySqlClient.MySqlConnection
$myconnection.ConnectionString = "server=172.30.30.90;port=3306;userid=user;password=pwd123;database=db1;pooling=false"
$myconnection.Open()

$mycommand = New-Object MySql.Data.MySqlClient.MySqlCommand
$mycommand.Connection = $myconnection
$mycommand.CommandText = "SELECT ip FROM vmip WHERE id > 1 LIMIT 1"

$myreader = $mycommand.ExecuteReader()
while($myreader.Read()){ $myreader.GetString(0) }

$myreader = $NewVMIP

# CLONE THE VM #

$TemplateVM = "Windows QA - 172.30.30.110 - TEMPLATE"
$NewVMFor = Read-Host "Please input Who This VM is For?"
$NewVMDate = Read-Host "Please input todays date"
$NewVMName = "Windows QA - $NewVMIP - $NewVMFor - $NewVMDate"

New-VM -Name $NewVMName -VM $TemplateVM -VMHost "esxfo01.jhcllp.local"
Move-VM -VM $NewVMName -Destination "Windows QA"
Start-VM -VM $NewVMName

# APPLY IP TO VM #

$username = "USER123"
$password = "PASS123"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr


Invoke-Command -ComputerName 172.30.30.110 -ScriptBlock {
    param($NewVMIP)

    $subnet = "255.255.255.0"
    $gateway = "172.30.30.1"

    netsh int ip set address "Local Area Connection" static "$NewVMIP" "255.255.255.0" "172.30.30.1"

} -credential $cred -ArgumentList $NewVMIP

As mentioned, it always acts as though the variable 'NewVMIP' is empty.

Thank you in advance for your help.

Marc Clar
  • 1
  • 1
  • 2

1 Answers1

1

I think you just a have a typo here. According to your code $NewVMIP is null since you never populate it.

Should $myreader = $NewVMIP not be $NewVMIP = $myreader instead maybe? Even if I'm wrong about that fix the fact remains that I never see where you populate the $NewVMIP variable.

Matt
  • 45,022
  • 8
  • 78
  • 119
  • +1, and here's [something else](http://stackoverflow.com/a/27021847/1751302) to keep in mind working with IPs in Powershell. You've got quotes, and it seems like you should be getting a string from MySQL, but the data type might be worth double-checking, or casting explicitly. – noam Apr 17 '15 at 13:49