Open up your PowerShell console, the PowerShell ISE, or your favorite PowerShell editor.
You will need to note what your instance name is. If you have a default instance, you can use your machine name. If you have a named instance, the format will be <machine name>\<instance name>
.
Before you can access or manipulate SQL Server programmatically, you will often need to create references to its objects. At the most basic is the server.
The server instance uses the type Microsoft.SqlServer.Management.Smo.Server
. By default, connections to the server are made using trusted connections, meaning it uses the Windows account you're currently using when you log into the server. So all it needs is the instance name in its argument list:
If, however, you need to connect using a SQL login, you will need to set the ConnectionContext.LoginSecure
property of the SMO Server class setting to false
:
You will also need to explicitly set the username and the password. The best way to accomplish this is to prompt the user for the credentials.
The credential window will capture the login and password. The Get-Credential
cmdlet returns the username with a leading backslash if the domain is not specified. In this case, we want to remove this leading backslash.
Once we have the login, we can pass it to the set_Login
method. The password is already a SecureString
type, which is what the set_SecurePassword
expects, so we can readily pass this to the method:
Should you want to hardcode the username and just prompt for the password, you can also do this:
In the script, you will also notice we are using Write-Verbose
instead of Write-Host
to display our results. This is because we want to be able to control the output without needing to always go back to our script and remove all the Write-Host
commands.
By default, the script will not display any output, that is, the $VerbosePreference
special variable is set to SilentlyContinue
. If you want to run the script in verbose mode, you simply need to add this line in the beginning of your script:
When you are done, you just need to revert the value to SilentlyContinue
: