Powershell script to change service account

前端 未结 10 2340
小蘑菇
小蘑菇 2020-12-15 03:07

Does anyone have a Powershell script to change the credentials used by a Windows service?

相关标签:
10条回答
  • 2020-12-15 03:17

    I wrote a function for PowerShell that changes the username, password, and restarts a service on a remote computer (you can use localhost if you want to change the local server). I've used this for monthly service account password resets on hundreds of servers.

    You can find a copy of the original at http://www.send4help.net/change-remote-windows-service-credentials-password-powershel-495

    It also waits until the service is fully stopped to try to start it again, unlike one of the other answers.

    Function Set-ServiceAcctCreds([string]$strCompName,[string]$strServiceName,[string]$newAcct,[string]$newPass){
      $filter = 'Name=' + "'" + $strServiceName + "'" + ''
      $service = Get-WMIObject -ComputerName $strCompName -namespace "root\cimv2" -class Win32_Service -Filter $filter
      $service.Change($null,$null,$null,$null,$null,$null,$newAcct,$newPass)
      $service.StopService()
      while ($service.Started){
        sleep 2
        $service = Get-WMIObject -ComputerName $strCompName -namespace "root\cimv2" -class Win32_Service -Filter $filter
      }
      $service.StartService()
    }
    
    0 讨论(0)
  • 2020-12-15 03:20

    What I cannot find in the default PS stack, I find it implemented in Carbon:

    http://get-carbon.org/help/Install-Service.html

    http://get-carbon.org/help/Carbon_Service.html (Carbon 2.0 only)

    0 讨论(0)
  • 2020-12-15 03:21

    Bit easier - use WMI.

    $service = gwmi win32_service -computer [computername] -filter "name='whatever'"
    $service.change($null,$null,$null,$null,$null,$null,$null,"P@ssw0rd")
    

    Change the service name appropriately in the filter; set the remote computer name appropriately.

    0 讨论(0)
  • 2020-12-15 03:21

    The PowerShell 6 version of Set-Service now has the -Credential parameter.

    Here is an example:

    $creds = Get-Credential
    Set-Service -DisplayName "Remote Registry" -Credential $creds
    

    At this point, it is only available via download via GitHub.

    Enjoy!

    0 讨论(0)
  • 2020-12-15 03:23

    Sc config example. First allowing modify access to a certain target folder, then using the locked down "local service" account. I would use set-service -credential, if I had PS 6 or above everywhere.

    icacls c:\users\myuser\appdata\roaming\fahclient /grant "local service:(OI)(CI)(M)"
    sc config "FAHClient" obj="NT AUTHORITY\LocalService"
    
    0 讨论(0)
  • 2020-12-15 03:24

    A slight variation on the other scripts here, is below. This one will set credentials for any/all services running under a given login account. It will only attempt to restart the service if it was already running, so that we don't accidentally start a service that was stopped for a reason. The script has to be run from and elevated shell (if the script starts telling you about ReturnValue = 2, you're probably running it un-elevated). Some usage examples are:

    • all services running as the currently logged in user, on the local host:

      .\set-servicecredentials.ps1 -password p@ssw0rd

    • all services running as user: somedomain\someuser on host somehost.somedomain:

      .\set-servicecredentials.ps1 somehost.somedomain somedomain\someuser p@ssw0rd

    Set-ServiceCredentials.ps1:

    param (
      [alias('computer', 'c')]
      [string] $computerName = $env:COMPUTERNAME,
    
      [alias('username', 'u')]
      [string] $serviceUsername = "$env:USERDOMAIN\$env:USERNAME",
    
      [alias('password', 'p')]
      [parameter(mandatory=$true)]
      [string] $servicePassword
    )
    Invoke-Command -ComputerName $computerName -Script {
      param(
        [string] $computerName,
        [string] $serviceUsername,
        [string] $servicePassword
      )
      Get-WmiObject -ComputerName $computerName -Namespace root\cimv2 -Class Win32_Service | Where-Object { $_.StartName -eq $serviceUsername } | ForEach-Object {
        Write-Host ("Setting credentials for service: {0} (username: {1}), on host: {2}." -f $_.Name, $serviceUsername, $computerName)
        $change = $_.Change($null, $null, $null, $null, $null, $null, $serviceUsername, $servicePassword).ReturnValue
        if ($change -eq 0) {
          Write-Host ("Service Change() request accepted.")
          if ($_.Started) {
            $serviceName = $_.Name
            Write-Host ("Restarting service: {0}, on host: {1}, to implement credential change." -f $serviceName, $computerName)
            $stop = ($_.StopService()).ReturnValue
            if ($stop -eq 0) {
              Write-Host -NoNewline ("StopService() request accepted. Awaiting 'stopped' status.")
              while ((Get-WmiObject -ComputerName $computerName -Namespace root\cimv2 -Class Win32_Service -Filter "Name='$serviceName'").Started) {
                Start-Sleep -s 2
                Write-Host -NoNewline "."
              }
              Write-Host "."
              $start = $_.StartService().ReturnValue
              if ($start -eq 0) {
                Write-Host ("StartService() request accepted.")
              } else {
                Write-Host ("Failed to start service. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa393660(v=vs.85).aspx" -f $start) -ForegroundColor "red"
              }
            } else {
              Write-Host ("Failed to stop service. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa393673(v=vs.85).aspx" -f $stop) -ForegroundColor "red"
            }
          }
        } else {
          Write-Host ("Failed to change service credentials. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa384901(v=vs.85).aspx" -f $change) -ForegroundColor "red"
        }
      }
    } -Credential "$env:USERDOMAIN\$env:USERNAME" -ArgumentList $computerName, $serviceUsername, $servicePassword
    
    0 讨论(0)
提交回复
热议问题