[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | out-null
$SMOWmiserver = New-Object ('Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer') "WIN7NetBook" #Suck in the server you want
#These just act as some queries about the SQL Services on the machine you specified.
$SMOWmiserver.Services | select name, type, ServiceAccount, DisplayName, Properties, StartMode, StartupParameters | Format-Table
#Same information just pivot the data
$SMOWmiserver.Services | select name, type, ServiceAccount, DisplayName, Properties, StartMode, StartupParameters | Format-List
#Specify the "Name" (from the query above) of the one service whose Service Account you want to change.
$ChangeService=$SMOWmiserver.Services | where {$_.name -eq "MSSQLSERVER"} #Make sure this is what you want changed!
#Check which service you have loaded first
$ChangeService
$UName="DomainName\UserName"
$PWord="YourPassword"
$ChangeService.SetServiceAccount($UName, $PWord)
#Now take a look at it afterwards
$ChangeService
# THIS WILL RESTART YOUR SQL SERVER SERVICE
$credential = Get-Credential -Message 'Provide the username (domain\username) and password for the SQL Server service account to run under';
$SqlServiceAccountParams = @{
ServerName = 'localhost'
InstanceName = 'MSSQLSERVER'
ServiceType = 'DatabaseEngine'
ServiceAccount = $credential
RestartService = $true
};
# Required to be able to run the
Install-Module 'SqlServerDsc';
$scriptBlock = {
$ErrorActionPreference = 'stop';
throw "I understand that this will RESTART THE SQL SERVER. Remove this line if you understand that your SQL Server will restart and are ready for the restart.";
Invoke-DscResource -Name 'SqlServiceAccount' -ModuleName 'SqlServerDsc' -Method Set -Property $SqlServiceAccountParams;
}
invoke-command $scriptBlock
然后输入您希望 SQL Server 登录的帐户。单击检查名称,以确保帐户存在。然后在选择用户或组上单击确定,然后在 SQL Server 属性上单击确定。
比重启。
2.This blog嘿,脚本专家!博客,作者Aaron Nelson - SQLvariant展示了如何在 PowerShell 中执行此操作。
Microsoft 为 Powershell Desired State Configuration (DSC) 发布了一个 SQL Server 模块,您可以使用它来更改 SQL Server 服务帐户。
我只用 Powershell 5 对此进行了测试,所以我不知道它与 Powershell Core 的工作情况如何,所以您可能会遇到
请注意,这将重新启动您的 SQL SERVER。
Powershell DSC - https://learn.microsoft.com/en-us/powershell/dsc/getting-started/wingettingstarted?view=dsc-1.1
SQL Server Powershell DSC 模块 - https://github.com/dsccommunity/SqlServerDsc