<<< Back to Search

Database

Execute SQL Query using Connection String

Execute SQL Script for a given Server/Database on Trusted Connection using Connection String

# Parameters
$databaseServer = "DESKTOP-XXXXX"
$database = "master"

# Connection string based on Trusted connection
$connectionString = "Server=$databaseServer;Database=$database;Trusted_Connection=True;"
    
# Execute SQL Query -_-    
Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery" -ConnectionString $connectionString -Verbose

PS C:\>

TimeOfQuery        
-----------        
4/3/2021 9:52:07 AM

Execute SQL Query using Named Instance

Execute SQL Script for a given Server/Database on Trusted Connection using Named Instance

# Parameters
$serverInstance = "DESKTOP-XXXXX"
$database = "master"
    
# Execute SQL Query -_-    
Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery" -ServerInstance $serverInstance -Database $database -Verbose

PS C:\>

TimeOfQuery        
-----------        
4/3/2021 9:49:57 AM