Need to loop twice through the query function below loading the results into two seperate variables. The query function works as expected, but need to have two unique queries stored in the two temp tables. How should I create these temporary tables that allow me to reference them as $1_resultsDataTable and $2_resultsDataTable? I will use these two tables to do a compare-object once I can successfully populate these TempTables.
[string] $Server= "ServerName" [string] $Database = "mvTest" [string] $UserSqlQuery= $("select statement") #Check Twice the database for Device Errors $Tables = @($1_resultsDataTable,$2_resultsDataTable) foreach ($resultsDataTable in $Tables) { $resultsDataTable = New-Object System.Data.DataTable $resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery Start-Sleep 5 } # declaration not necessary, but good practice #$resultsDataTable = New-Object System.Data.DataTable #$resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery # executes a query and populates the $datatable with the data function ExecuteSqlQuery ($Server, $Database, $SQLQuery) { $Datatable = New-Object System.Data.DataTable $Connection = New-Object System.Data.SQLClient.SQLConnection $Connection.ConnectionString = "server='$Server';database='$Database';Integrated Security=True;" $Connection.Open() $Command = New-Object System.Data.SQLClient.SQLCommand $Command.Connection = $Connection $Command.CommandText = $SQLQuery $Reader = $Command.ExecuteReader() If ($Reader.HasRows) { while($Reader.Read()) { $props = @{} for($i = 0; $i -lt $Reader.FieldCount; $i+=1) { $name = $Reader.GetName($i) $value = $Reader.item($i) $props.Add($name, $value) } $obj = new-object PSObject -Property $props Write-Output $obj } } return $obj $SqlConnection.Close() }
Advertisement
Answer
Not sure why you would specifically need to use named variables instead of just assigning to an array, but you could just list both variables to be assigned to the output of your loop and then loops twice.
$1_resultsDataTable, $2_resultsDataTable = foreach ($x in 1..2) { $resultsDataTable = New-Object System.Data.DataTable $resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery $resultsDataTable # first loop sends output to $1_resultsDataTable, second loop send to $2_resultsDataTable Start-Sleep 5 }
You could still do compare without named variables using an array instead
$bothTables = foreach ($x in 1..2) { $resultsDataTable = New-Object System.Data.DataTable $resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery $resultsDataTable # first loop sends output to $1_resultsDataTable, second loop send to $2_resultsDataTable Start-Sleep 5 } Compare-Object -ReferenceObject $bothTables[0] -DifferenceObject $bothTables[1]