首页 > 解决方案 > Power Shell 将 SQL 查询结果添加到数组或表中

问题描述

我有一个 Power Shell 脚本,它将连接到我的数据库并返回 10 个 ID 和相关代码的列表。运行此脚本时,它会列出 10 个 ID,然后是 10 个代码。我正在尝试将这些值放入一个数组中,以便稍后在脚本中循环浏览它们。

ps1:

clear

#################################################
## Connect to SQL Server Database
#################################################
[string]$serverName = 'Server'
[string]$databaseName = 'Database'
[string]$userName = 'Username'
[string]$password = 'Password'

$connectionString = 'Data Source={0};database={1};User ID={2};Password={3}' -f $serverName,$databaseName,$userName,$password

$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $connectionString
$sqlConnection.Open()

#################################################
## Run SQL Query
#################################################
[string]$sqlCommand = 'SELECT TOP 10 * FROM Table'

$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)

$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null

#################################################
## Return SQL Query Results
#################################################

$dataSet.tables.id
$dataSet.tables.code

#################################################
## Close SQL Connection
#################################################

$sqlConnection.Close()

目前输出看起来像:

1
2
3
4
5
code1
code2
code3
code4
code5

我试图让输出看起来像:

{
   ("1","code1"),
   ("2","code2"),
   ...
}

或以表格格式返回数据

标签: sql-serverpowershell

解决方案


尝试这个 :

$dataSet.tables | Select id, code

也看看Select-Object

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-object?view=powershell-6


推荐阅读