How to query SQL Server using PowerShell

I have this code that I got from a website and it's connected to my SQL Server using window authentication but I'm not sure how can I choose a database and query some table?.

[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-Null
$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') "server instance"
$s.ConnectionContext.LoginSecure=$true
$s.Databases | select name, size, status

If I run this code, it show me a list of databases but I want to choose a database called "LitHold" and query some table from that database inside.


For SMO like you have in your question, you can run queries that return data using ExecuteWithResults() like so:

$s =  New-Object Microsoft.SqlServer.Management.Smo.Server "server instance"
$db = $s.Databases.Item("master")

$query = "SELECT * FROM [master].[sys].[databases] ORDER BY [name];"
$result = $db.ExecuteWithResults($query)

# Show output
$result.Tables[0]