1

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.

7
  • If you can install Modules, I would take on this module powershellgallery.com/packages/SqlServer/21.1.18256 Commented Jan 13, 2022 at 20:12
  • Hi @SantiagoSquarzon, I already installed that module tho. Commented Jan 13, 2022 at 20:20
  • 2
    The module contains the Invoke-Sqlcmd command; I would suggest having a look at that. Commented Jan 13, 2022 at 20:22
  • 2
    DBAtools is another very recommended module but haven't tried it personally. Commented Jan 13, 2022 at 20:23
  • 1
    I'd assume so, as you don't create the connection yourself; it's all encapsulated inside the module. Though you could easily test this out, @HarvB . Commented Apr 4, 2024 at 15:22

1 Answer 1

3

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]
Sign up to request clarification or add additional context in comments.

2 Comments

It work, thank you so much bro. really appreciate it.
Hi bro, can you please answer another question for me. stackoverflow.com/questions/70705126/…

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.