To run this script, SSH public key authentication must be set up and enabled between the gateway server and the target server.
Copy $ScheduledTaskName = '<Task Name>'
$TargetMachine = '<Target Machine>'
$SSHUsername = '<SSH Username>'
Updating the Scheduled Task
Native SSH remoting is still not fully implemented into PowerShell and is only reliably possible in PowerShell 7. The gateway defaults to Windows PowerShell (v5) when running a .ps1
script. However, when attaching the script, you can also specify an alternative script command and point to the path of your PowerShell 7 executable.
Once the rotation is complete, we will log the service status to DEBUG.
Copy $ScheduledTaskStatus = Invoke-Command `
- HostName $TargetMachine `
- UserName $SSHUsername `
- ScriptBlock { `
Stop-ScheduledTask - TaskName $ Using :ScheduledTaskName; `
Set-ScheduledTask -TaskName $Using:ScheduledTaskName -User $Using:Params.user -Password $Using:Params.newPassword; `
Start-ScheduledTask - TaskName $ Using :ScheduledTaskName; `
return Get-ScheduledTask $ Using :ScheduledTaskName | Select-Object - ExpandProperty "State" ;
}
Write-Debug "$ScheduledTaskName is: $ ($ScheduledTaskStatus.State) "
Copy [ CmdletBinding ()]
param (
[ Parameter (ValueFromPipeline = $true )]
[ string ]
$Record
)
# User defined parameters
$ErrorActionPreference = "Stop"
$DebugPreference = 'Continue'
$ScheduledTaskName = '<Task Name>'
$TargetMachine = '<Target Machine>'
$SSHUsername = '<SSH Username>'
$RecordJsonAsB64 = [ System.Text.Encoding ]::UTF8.GetString([ System.Convert ]::FromBase64String($Record))
$Params = ($RecordJsonAsB64 | ConvertFrom-Json - ErrorAction Stop)
Write-Debug "Running Post-Rotation Script on = $ ($Params.userRecordUid) "
$ScheduledTaskStatus = Invoke-Command `
- HostName $TargetMachine `
- UserName $SSHUsername `
- ScriptBlock { `
Stop-ScheduledTask - TaskName $ Using :ScheduledTaskName; `
Set-ScheduledTask -TaskName $Using:ScheduledTaskName -User $Using:Params.user -Password $Using:Params.newPassword; `
Start-ScheduledTask - TaskName $ Using :ScheduledTaskName; `
return Get-ScheduledTask $ Using :ScheduledTaskName | Select-Object - ExpandProperty "State" ;
}
Write-Debug "$ScheduledTaskName is: $ ($ScheduledTaskStatus.State) "