PowerShell Example via WinRPC

Using Admin Credentials

To update the 'Log On As' property on a Windows Scheduled Task, you will need a credential with the appropriate permissions, such as an Administrator account.

When attaching a PAM script to a record, you have the option to add a Resource Credential that is passed to the Gateway as part of the BASE64-encoded JSON data. The above credential will need to be attached as a Resource Credential.

As many Resource Credentials can be attached to a PAM script, knowing the UID of the Resource Credential you have attached helps ensure your script uses the correct one to update the Service's 'Log On As' property.

Updating the Scheduled Task

You can use the schtasks command to update the credentials on the Scheduled Task. This command also requires the admin credentials mentioned above to perform the task.

schtasks /change /tn $ScheduledTaskName /s '<Target Machine>' /u $AdminUserName /p $AdminRecord.password /ru $Params.user /rp $Params.newPassword

Unfortunately, as the schtasks 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 schtasks command, the gateway will always show success. To solve for this, you can check $LastExitCode after each call to schtasks.

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

Full Example

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

$ErrorActionPreference = "Stop"
$DebugPreference = 'Continue'

function ConvertFrom-B64 {
    param (
        [string] $B64String
    )

    try {
        $Json = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($B64String))
        $Output = $Json | ConvertFrom-Json
    }
    catch {
        Write-Error "Failed to convert Base64 string: $B64String"
    }
    return $Output
}

# The JSON data is passed to the Gateway as a Base64 encoded string.
$Params = ConvertFrom-B64 -B64String $B64Input
Write-Debug "Running Post-Rotation Script on: $($Params.userRecordUid)" 

# Convert the attached Resource Records from Base64 encoded JSON string and find the 
# Admin Record we need to update the Service's `Log On As` property by filtering by the 
# Admin Record's UID.
$ResourceCredentials = ConvertFrom-B64 -B64 $Params.records
$AdminRecord = $ResourceCredentials | Where-Object { $_.uid -eq '<Admin Record UID>' }
$AdminUserName = "$($AdminRecord.login)@$($AdminRecord.domainName)"

$ScheduledTaskName = '<Scheduled Task Name>'
Write-Debug "Updating Scheduled Task: $ScheduledTaskName"
schtasks /change /tn $ScheduledTaskName /s '<Target Machine>' /u $AdminUserName /p $AdminRecord.password /ru $Params.user /rp $Params.newPassword
if( $LastExitCode -ne 0 ) { 
    exit $LastExitCode 
}

Last updated