使用 Powershell 更改 SQL Server 服务帐户

发布于 2024-12-05 06:37:43 字数 828 浏览 1 评论 0原文

我已经准备了以下脚本以更改SQL Server服务帐户。但是,当我在脚本下运行时,服务不会停止并开始。有Diea吗?有没有贝特的方法来做到这一点。是否有其他替代人的睡眠。我们不知道停止和开始需要多少服务。有没有办法让Powershell等待直到完全服务 停止/开始。

$Services = Get-WmiObject Win32_Service -ComputerName "." | Where { $_.name -eq 'MSSQLSERVER' }    
ForEach($Service in $Services)    
{             
$StopStatus = $Service.StopService()
Sleep 15
If ($StopStatus.ReturnValue -eq "0")
 {write-host "$Service -> Service Stopped Successfully"} 
$ChangeStatus = $Service.change($null,$null,$null,$null,$null,$null,$ServiceAccount,$Password,$null,$null,$null)
If ($ChangeStatus.ReturnValue -eq "0")
 {write-host "$Service -> Sucessfully Changed Service Account"}
$StartStatus = $Service.StartService()
Sleep 25
If ($ChangeStatus.ReturnValue -eq "0")
{write-host "$Service -> Service Started Successfully"}
}

I have prepared below script to change sql server service account. But the service is not stopping and starting when i run below script. Any diea? is there any beeter way to do this. is there any alternative for Sleep. We don't know how much service takes to stop and start. Is there a way to keep powershell to wait until service completely
stops/starts.

$Services = Get-WmiObject Win32_Service -ComputerName "." | Where { $_.name -eq 'MSSQLSERVER' }    
ForEach($Service in $Services)    
{             
$StopStatus = $Service.StopService()
Sleep 15
If ($StopStatus.ReturnValue -eq "0")
 {write-host "$Service -> Service Stopped Successfully"} 
$ChangeStatus = $Service.change($null,$null,$null,$null,$null,$null,$ServiceAccount,$Password,$null,$null,$null)
If ($ChangeStatus.ReturnValue -eq "0")
 {write-host "$Service -> Sucessfully Changed Service Account"}
$StartStatus = $Service.StartService()
Sleep 25
If ($ChangeStatus.ReturnValue -eq "0")
{write-host "$Service -> Service Started Successfully"}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ペ泪落弦音 2024-12-12 06:37:43

您可以查看该服务是否在循环中停止(或开始),然后继续进行:

$sleepCounter = 1
While((Get-Service $serviceName).status -ne "Stopped" ){
        Write-Host "Waiting for service to stop. Attempt $sleepCounter of 20"
        sleep 1
        if($sleepCounter -eq 20) { break }
        $sleepCounter++
}

另外,您可以执行以下操作以获取服务,而不是使用where-object

$svc=gwmi win32_service -filter "name='$serviceName'"

You can see if the service is stopped ( or started ) in a loop and then proceed:

$sleepCounter = 1
While((Get-Service $serviceName).status -ne "Stopped" ){
        Write-Host "Waiting for service to stop. Attempt $sleepCounter of 20"
        sleep 1
        if($sleepCounter -eq 20) { break }
        $sleepCounter++
}

Also, you can do the following to get the service instead of using where-object

$svc=gwmi win32_service -filter "name='$serviceName'"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文