Here’s a quick post detailing a PowerShell script that can be used to change the
password for a SQL Server
Login.
Regular readers know that I practice the philosophy of
Automate Everything and DBA administrative tasks are no exception. I don’t want to be doing the same task by hand twice, if I can help it.
A requirement came up recently where I had the need to change a
number of SQL Server Logins on multiple SQL Server instances. That’s
just the sort of
exciting work that PowerShell can be used for.
Below you’ll find a script that I threw together in order to complete
the task. It accepts a list of server/instance names as a text file,
and then you enter the SQL Server Login
name and
password as parameters on the command line. You don’t want to be storing those in a text file right!
param([String] $serverListPath , [String] $login , [String] $password ) |
$ServerNameList = get-content -path $serverListPath |
[System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.SqlServer.Smo" ) | Out-Null |
$objSQLConnection = New-Object System.Data.SqlClient.SqlConnection |
foreach ( $ServerName in $ServerNameList ) |
$objSQLConnection .ConnectionString = "Server=$ServerName;Integrated Security=SSPI;" |
Write-Host "Trying to connect to SQL Server instance on $ServerName..." -NoNewline |
$objSQLConnection .Open() | Out-Null |
$objSQLConnection .Close() |
Write-Host -BackgroundColor Red -ForegroundColor White "Fail" |
$errText = $Error [0].ToString() |
if ( $errText .Contains( "network-related" )) |
{ Write-Host "Connection Error. Check server name, port, firewall." } |
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $ServerName |
$SQLUser = $srv .Logins | ? {$_.Name -eq "$login" }; |
$SQLUser .ChangePassword( $password ); |
$SQLUser .PasswordPolicyEnforced = 1; |
Write-Host "Password for Login:'$login' changed sucessfully on server:'$ServerName' " |
0 Commentaires