1+ # HT http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/03/use-powershell-to-change-sql-server-s-service-accounts.aspx
2+ [System.Reflection.Assembly ]::LoadWithPartialName(' Microsoft.SqlServer.SqlWmiManagement' )| Out-Null
3+ function Set-SqlServiceAccount {
4+ param ([string []] $Instance
5+ , [System.Management.Automation.PSCredential ]$ServiceAccount
6+ , [ValidateSet (' SqlServer' , ' SqlAgent' )] $service = ' SqlServer'
7+ )
8+
9+ # Get Service Account name from credential object
10+ $account = $ServiceAccount.GetNetworkCredential ().Domain + ' \' + $ServiceAccount.GetNetworkCredential ().UserName
11+
12+ # Loop through and change instances
13+ foreach ($i in $Instance ){
14+ # Parse host and instance names
15+ $HostName = ($i.Split (' \' ))[0 ]
16+ $InstanceName = ($i.Split (' \' ))[1 ]
17+
18+ # Get service account names, set service account for change
19+ $sqlsvc = if ($InstanceName ){" MSSQL`$ $InstanceName " }else {' MSSQLSERVER' }
20+ $agtsvc = if ($InstanceName ){" SQLAGENT`$ $InstanceName " }else {' SQLSERVERAGENT' }
21+
22+ $ServiceName = switch ($service ){
23+ ' SqlServer' {$sqlsvc }
24+ ' SqlAgent' {$agtsvc }
25+ }
26+
27+ # Use wmi to change account
28+ $smowmi = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $HostName
29+ $wmisvc = $smowmi.Services | Where-Object {$_.Name -eq $ServiceName }
30+ $wmisvc.SetServiceAccount ($account , $ServiceAccount.GetNetworkCredential ().Password)
31+
32+ # If Agent service isn't running (happens if you reset SQL Service), start it
33+ $wmiagt = $smowmi.Services | Where-Object {$_.Name -eq $agtsvc }
34+ if ($wmiagt.ServiceSatus -ne ' Running' ){$wmiagt.Start ()}
35+ }
36+ }
37+
38+
39+ <#
40+ $cred = Get-Credential 'Enter Service Account'
41+ Set-SqlServiceAccount -Instance PICARD -ServiceAccount $cred -Service SqlServer
42+ #>
0 commit comments