Skip to content

Instantly share code, notes, and snippets.

@w3bward
Last active March 27, 2022 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w3bward/0844df5ec5585c507fbb248eaa84404d to your computer and use it in GitHub Desktop.
Save w3bward/0844df5ec5585c507fbb248eaa84404d to your computer and use it in GitHub Desktop.
SMO example using an AD (or AAD) username and password for authentication
$Server = "myazuresqlserver.database.windows.net"
$Database = "MyDatabase"
$Credential = Get-Credential
# Step 1, create the SqlConnectionInfo object
$ConnectionInfo = [Microsoft.SqlServer.Management.Common.SqlConnectionInfo]::new($Server)
$ConnectionInfo.DatabaseName = $Database
$ConnectionInfo.Authentication = [Microsoft.SqlServer.Management.Common.SqlConnectionInfo+AuthenticationMethod]::ActiveDirectoryPassword
$ConnectionInfo.SecurePassword = $Credential.Password
$ConnectionInfo.UserName = $Credential.UserName
# Step 2, create the ServerConnection object
$ServerConnection = [Microsoft.SqlServer.Management.Common.ServerConnection]::new($ConnectionInfo)
# Step 3 Create the SMO Server object
$ServerInstance = [Microsoft.SqlServer.Management.Smo.Server]::new($ServerConnection)
# (Optional) Step 4 Get an object representing the target database
$DatabaseInstance = $ServerInstance.Databases | where Name -EQ $Database
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment