5

I can't believe it, but all indications are that my PowerShell code is returning the result of a SELECT query that finds 1 record as an object, but if there are two or more records the same code returns an array of objects. What am I doing wrong?

Below is the code:

function Connect-MySQL([string]$MySQLHost, [string]$user, [string]$pass, [string]$database) { 
    Write-Verbose "Connect-MySQL"
    # Load MySQL .NET Connector Objects 
    [void][system.reflection.Assembly]::LoadWithPartialName("MySql.Data") 

    # Open Connection 
    $connStr = "server=$MySQLHost;port=3306;uid=$user;pwd=$pass;database=$database;Pooling=FALSE" 
    try {
        $con = New-Object MySql.Data.MySqlClient.MySqlConnection($connStr) 
        $con.Open()
    } catch [System.Management.Automation.PSArgumentException] {
        Write-Verbose "Unable to connect to MySQL server, do you have the MySQL connector installed..?"
        Write-Verbose $_
        Exit
    } catch {
        Write-Verbose "Unable to connect to MySQL server..."
        Write-Verbose $_.Exception.GetType().FullName
        Write-Verbose $_.Exception.Message
        exit
    }
    Write-Verbose "Connected to MySQL database $MySQLHost\$database"

    return $con 
}

function Disconnect-MySQL($con) {
    Write-Verbose "Disconnect-MySQL"
    $con.Close()
}

function Execute-MySQLNonQuery($con, [string]$sql) { 
    $cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($sql, $con)            # Create SQL command
    $Rows = $cmd.ExecuteNonQuery()                                               # Execute command
    $cmd.Dispose()                                                               # Dispose of command object
#   if ($Rows) { 
        return $Rows
#   } else { 
#       return $false 
#   } 
} 

function Execute-MySQLQuery($con, [string]$sql) { 
    $cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($sql, $con)            # Create SQL command
    $dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($cmd)      # Create data adapter from query command
    $dataSet = New-Object System.Data.DataSet                                    # Create dataset
    $dataAdapter.Fill($dataSet, "data") | Out-Null                               # Fill dataset from data adapter, with name "data"              
    $cmd.Dispose()                                                               # Dispose of command object
    return $dataSet.Tables["data"]                                               # Returns an array of results
}


# Connection Variables 
$MySQLHost = '10.10.10.111' 
$user = 'user' 
$pass = 'test' 
$database = 'test_db' 

# Connect to MySQL Database 
$con = Connect-MySQL $MySQLHost $user $pass $database

# Get requests
$sql = "
SELECT *
FROM o365_statuses as x
WHERE x.action = 'Z'
AND x.status = 0"
$result = Execute-MySQLQuery $con $sql

Write-Host $result.Count
Foreach ($r in $result) {
    write-host "$($r.id) $($r.email)"
}

When $result is only 1 record, $result.Count returns nothing, and I can access the columns as $result.id and not $result[0].id. If there are 2 or more records returned the opposite is true.

Please tell me I'm doing something wrong, and that this is not the way PowerShell works.

4

2 回答 2

5

PowerShell 根据这个简单的算法返回结果:

  • 多个项目 --> 返回这些项目的数组
  • 仅一项 --> 退回该项

通常,强制 PowerShell 始终返回一个数组是一种很好的做法,使用以下任一方法:

,(code)
@(code)

但是,这些运算符并不相同!您可以安全地将@()分组运算符应用于任何东西以强制数组输出——数组总是有一个Count属性,例如:

$a = @(Get-Process | select -First 2); $a.Count   # returns 2
$a = @(Get-Process | select -First 1); $a.Count   # returns 1

另一方面,逗号数组构造运算符的工作方式如下:

$a = ,(Get-Process | select -First 2); $a.Count   # returns 1
$a = ,(Get-Process | select -First 1); $a.Count   # returns 1

...因为它使用给定的任何内容构建一个嵌套数组。

于 2012-10-31T20:21:55.197 回答
1

一个函数“展开”返回的集合,即实际上它返回 null(0 个项目)或单个对象(它可能具有也可能不具有属性Count,在您的情况下它没有)或 2+ 个对象的数组(但不是原始集合实例)。

为了解决展开使用,操作符:

return , $Rows

逗号运算符创建单个对象(操作数)的数组,即一个新集合。这个新集合也在返回时展开,但不是递归展开。那就是返回一个对象,它是$Rows原样的,相同的实例。

于 2012-10-29T06:28:07.807 回答