Skip to content

Instantly share code, notes, and snippets.

@ghotz
Created May 27, 2014 12:19
Show Gist options
  • Save ghotz/ef6cb25c50174730d606 to your computer and use it in GitHub Desktop.
Save ghotz/ef6cb25c50174730d606 to your computer and use it in GitHub Desktop.
Connect to a SQL Server instance
[Void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO');
[Void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended');
function Get-SQLInstance($InstanceName, $Login, $Password)
{
$SQLInstance = New-Object "Microsoft.SqlServer.Management.Smo.Server" $InstanceName;
if ($Login -eq $null) {
$SQLInstance.ConnectionContext.LoginSecure = $true;
}
else {
$SQLInstance.ConnectionContext.LoginSecure = $false;
$SQLInstance.ConnectionContext.Login = $Login;
$SQLInstance.ConnectionContext.Password = $Password;
};
# Force connection to get an early error message
$SQLInstance.ConnectionContext.Connect();
return $SQLInstance;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment