PowerShell Example via WinRPC (英語)

日本語ページを作成しております。今しばらくお待ちください。

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'

Updating the Service

You can decode the BASE64 string and convert it to a useable PowerShell object with:

$RecordJsonAsB64 = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Record))
$RecordParams = ($RecordJsonAsB64 | ConvertFrom-Json)

The sc.exe command is used to update the desired Windows service using the values extracted from the JSON.

Note: sc is an aliase in Windows PowerShell for Set-Content. Therefore you must include the file extension or provide a full path to the executable.

After updating the Windows Service, we will restart it, which will confirm that the credentials have been updated successfully.

sc.exe \\$TargetMachine stop $ServiceName
sc.exe \\$TargetMachine config $ServiceName obj= $RecordParams.user password= $RecordParams.newPassword
sc.exe \\$TargetMachine start $ServiceName

Note: The SC command has particular syntax. The whitespace after = matters! All server names must start with a double backslash.

Unfortunately, as the sc.exe command is not a PowerShell cmdlet, so its output will not be captured by $error. Without additional error checking, regardless of the exit status of the sc.exe command, the gateway will always show success. To solve for this, you can check $LastExitCode after each call to sc.exe.

if( $LastExitCode -ne 0 ) {
    exit $LastExitCode
}

Full Example

[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
if( $LastExitCode -ne 0 ) {
    exit $LastExitCode
}

Write-Debug "Changing $ServiceName password"
sc.exe \\$TargetMachine config $ServiceName obj= $($RecordParams.user) password= $($RecordParams.newPassword)
if( $LastExitCode -ne 0 ) {
    exit $LastExitCode
}

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

最終更新