title: Powershell query database and store results in a variable
body: <p>I have written a powershell script to query a database to get a list of server names. I then store the results in a variable so I can go through each server to lookup a service by doing something like: <code>foreach ($server in $servers)</code>. I have no issue storing the results in a variable but when I do a foreach statement, it doesn't let me retrieve the server name 1 by 1 properly. </p>
  
  <p>If I manually type out the server names like <code>$servers = (server, server2,server3)</code> then the <code>forEach</code> will work.
  What's the proper way of doing this?</p>
  
  <p>Updated:  Below is the script</p>
  
  <pre><code>$SQLServer= 'sourceServer'
  $Database = 'DatabaseNameHere'
  </code></pre>
  
  <p>Create a SQL Query function</p>
  
  <pre><code>Function SQL_Query ($Query) {
  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection 
  $SqlConnection.ConnectionString = 
  "Server=$SQLServer;Database=$Database;Integrated Security=True"
  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand 
  $SqlCmd.Connection = $SqlConnection 
  $SqlCmd.CommandText = $Query 
  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 
  $SqlAdapter.SelectCommand = $SqlCmd 
  $DataSet = New-Object System.Data.DataSet 
  $a=$SqlAdapter.Fill($DataSet) 
  $SqlConnection.Close() 
  $DataSet.Tables[0]  
  }
  </code></pre>
  
  <p>Use this function</p>
  
  <pre><code>$list=SQL_Query "Select ServerName From Server_Inventory Where Status = 'A' " 
  </code></pre>
  
  <p>Check returned Server list</p>
  
  <pre><code>$list
  </code></pre>
  
  <p>I would like to go through each server and see what servers are installed on each server</p>
  
  <pre><code>$output= Foreach ($server in $list) {
  $output=Get-DbaSqlService -ComputerName $server | Where-Object 
  {$_.ServiceType -in ('SSIS','Agent','Engine','SSRS','FullText')} 
  }
  $output | Out-GridView -Title "View all SQL Services"
  </code></pre>