Sql-server – Using Powershell get Values from sql table


we know that we can use sql query window to get values from Database like "select * from....". Is there any way to get a value through powershell way. I found the way to database table itself but not to the values..


Set-location SQLserver:\sql\default\localhost\databases\database\tablesGet-childitem 

Above command gives me tables in the DB , but how can i get the values from it.

Best Solution

You can use this

$connectionString = “Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;”

$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString

$query = “SELECT * FROM Tab”

$command = $connection.CreateCommand()
$command.CommandText = $query

$result = $command.ExecuteReader()