PowerShell Example via WinRPC

Rotating a Windows Service Credential using PowerShell

User Defined Parameters

In the below example, you will hard code two values:

  1. The name of the service for which you wish to rotate the credential.

  2. The DNS resolvable name of the server the service is running on.

$ServiceName = 'My Service'
$TargetMachine = 'my-server'

Example Script

[CmdletBinding()]
param (
    [Parameter(ValueFromPipeline=$true)]
    [string]
    $Record
)

# User defined parameters
$ErrorActionPreference = 'Stop'
$DebugPreference = 'Continue'
$ServiceName = 'My Service'
$TargetMachine =  'my-server'

$RecordJsonAsB64 = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Record))
$RecordParams = ($RecordJsonAsB64 | ConvertFrom-Json)
Write-Debug "Running Post-Rotation Script on = $($RecordParams.userRecordUid)"

Write-Debug "Stopping $ServiceName"
sc.exe \\$TargetMachine stop $ServiceName

# Wait for the service to stop with a timeout
$limit = 120
$count = 0
while ($count -lt $limit -and !$serviceStopped) {
    sc.exe \\$TargetMachine query $ServiceName | Select-String "STOPPED"
    if ($LastExitCode -eq 0) {
        $serviceStopped = $true
    } else {
        Start-Sleep -Seconds 1
        $count++
    }
}

if (!$serviceStopped) {
    Write-Debug "Service failed to stop within the timeout period."
    exit 1
}

Write-Debug "Service stopped, waiting 5 seconds"
Start-Sleep -Seconds 5

# Get the service using WMI
$service = Get-WmiObject -Class Win32_Service -ComputerName $TargetMachine -Filter "Name = '$ServiceName'"

# Ensure the username is in the ".\user" format if not already specified
$userName = $RecordParams.user
if ($userName -notmatch "^.+\\") {
    $userName = ".\$userName"
}

# Change the service account credentials
$status = $service.Change($null, $null, $null, $null, $null, $null, $userName, $($RecordParams.newPassword), $null, $null, $null)

# Output result
if ($status.ReturnValue -eq 0) {
    Write-Host "Service credentials updated successfully."
} else {
    Write-Host "Failed to update service credentials. Error code: $($service.ReturnValue)"
}

Write-Debug "Restarting $ServiceName"
sc.exe \\$TargetMachine start $ServiceName
if( $LastExitCode -ne 0 ) {
    exit $LastExitCode
}

Last updated