MSSQL PowerShell 测试db能不能连接

PS

# Define the connection string
$connectionString = "Server=XXX;Database=XXX;UID=XXX;Password=XXX;Encrypt=False;"

# Load the .NET SQL Client assembly
Add-Type -AssemblyName "System.Data"

# Create a new SQL connection object
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString

# Try to open the connection and execute the query
try {
    $connection.Open()
    Write-Host "Connection successful!"

    # Define the SQL query
    $query = "SELECT 1"

    # Create a SQL command object
    $command = $connection.CreateCommand()
    $command.CommandText = $query

    # Execute the query
    $result = $command.ExecuteScalar()
    Write-Host "Query executed successfully. Result: $result"
} catch {
    Write-Host "Connection failed: $_"
} finally {
    # Close the connection if it is open
    if ($connection.State -eq [System.Data.ConnectionState]::Open) {
        $connection.Close()
    }
}

 

posted @ 2025-09-10 17:19  Robot-Blog  阅读(8)  评论(0)    收藏  举报