0

I have a small PowerShell script that runs a query on about 30+ servers which pulls the server name and which version of SQL Server is installed. I then want to insert that data into a table but can't quite figure out how to do that with the returned data set my query returns. This is my code so far

$SvrNameList = @( invoke-sqlcmd -serverinstance MyServer -Database MyDB -Query "SELECT ServerName FROM ServerNames WHERE [Enabled] = 1"  ) | select-object -expand ServerName


foreach ( $i in $SvrNameList )
{
   invoke-sqlcmd -ServerInstance $i -Query "SELECT @@ServerName AS ServerName, @@Version AS Version" 
} 

Any help is appreciated

2
  • 3
    Why don't you write an INSERT .. SELECT query? Commented May 23, 2017 at 9:13
  • Because that would try insert 1 line on each of the servers as it is running the query once on each server. I want to insert all of the results into a table on 1 server. Commented May 23, 2017 at 9:24

1 Answer 1

2

First, add the instance names and versions into a hash table. After it's populated, you can do inserts into the result table. Like so,

$ht=@{} # Create empty hashtable
foreach ( $i in $SvrNameList ){
   $r = invoke-sqlcmd -ServerInstance $i -Query "SELECT s=@@ServerName, v=@@Version" # Query server names and versions 
   $ht.Add($r.s, $r.v) # Add name and version into hashtable
}

# Enumerate the hashtable and generate insert commands
$ht.GetEnumerator() | % {
    invoke-sqlcmd -ServerInstance foo -query "insert into t(s, v) values ('" + $_.value + "', '"+  $_.name +"');" 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Worked with a little tweaking. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.