Add SQL results to an array and reference it in Powershell

Christopher Jack 1,616 Reputation points
2021-02-02T12:04:35.407+00:00

Hi,

I have the following code,

  ## - Get SQL Server Table data:
$SQLServer = 'server';
$Database = 'database';

## - Connect to SQL Server using non-SMO class 'System.Data':
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection;
$SqlConnection.ConnectionString = `
"Server = $SQLServer; Database = $Database; Integrated Security = True";

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand;
$SqlCmd.CommandText = $("EXEC [zoomfs].[DPDHeaderExport]");
$SqlCmd.Connection = $SqlConnection;
$SqlCmd.CommandTimeout = 0;

## - Extract and build the SQL data object '$DataSetTable':
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);

$SqlConnection.Close()
$defaultdata = $DataSet.Tables[0].rows[0].data

for($i=0;$i -lt $DataSet.Tables[1].Rows.Count;$i++)
{ 
  write-host "value is : $i $($DataSet.Tables[1].Rows[$i][0])"
}

It just seems to write the count of the number of rows which is 70 to the output. It does not do the loop through?

How do I reference a row and value in the dataset?

Any help appreciated

Windows for business | Windows Server | User experience | PowerShell
Sysinternals
Sysinternals
Advanced system utilities to manage, troubleshoot, and diagnose Windows and Linux systems and applications.
1,243 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.