【问题标题】:Powershell: Using a SELECT from a MySQL DB as a variable in PowerCLIPowershell:使用 MySQL 数据库中的 SELECT 作为 PowerCLI 中的变量
【发布时间】:2015-04-16 15:37:40
【问题描述】:

我遇到了一个问题,我需要对我的 MySql 数据库运行查询(获取 IP 地址)并将结果放入变量中(用于克隆 VM)但是,这似乎不起作用变量变为空。 'NewVMIP' 变量最终应该包含来自 MySQL 数据库的 IP。访问数据库并选择信息时没有错误,问题似乎出在克隆VM时尝试使用变量时,它只是空白。

# 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

如前所述,它总是表现得好像变量“NewVMIP”为空。

提前感谢您的帮助。

【问题讨论】:

    标签: mysql powershell powercli


    【解决方案1】:

    我认为你只是在这里有一个错字。根据您的代码,$NewVMIP 为 null,因为您从未填充它。

    $myreader = $NewVMIP 不应该是$NewVMIP = $myreader 而不是吗?即使我对这个修复有误,但事实仍然是我永远看不到你在哪里填充 $NewVMIP 变量。

    【讨论】:

    • +1,这里是something else,请记住在 Powershell 中使用 IP。你有引号,看起来你应该从 MySQL 获取一个字符串,但是数据类型可能值得仔细检查,或者显式转换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    相关资源
    最近更新 更多