To run this script, SSH public key authentication must be set up and enabled between the gateway server and the target server.
コピー $ServiceName = '<Service Name>'
$TargetMachine = '<Target Server>'
$SSHUsername = '<Username>'
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.
コピー $ServiceStatus = Invoke-Command `
- HostName $TargetMachine `
- UserName $SSHUsername `
- ScriptBlock { `
Stop-Service - Name $ Using :ServiceName; `
Set-Service - Name $ Using :ServiceName - Credential $ Using :ServiceCredential; `
Start-Service - name $ Using :ServiceName; `
return Get-Service $ Using :ServiceName;
}
Write-Debug "$ServiceName is: $ ($ServiceStatus.Status) "
コピー [ CmdletBinding ()]
param (
[ Parameter (ValueFromPipeline = $true )]
[ string ]
$B64Input
)
# User defined parameters
$ErrorActionPreference = "Stop"
$DebugPreference = 'Continue'
$ServiceName = '<Service Name>'
$TargetMachine = '<Target Server>'
$SSHUsername = '<Username>'
$RecordJsonAsB64 = [ System.Text.Encoding ]::UTF8.GetString([ System.Convert ]::FromBase64String($B64Input))
$Params = ($RecordJsonAsB64 | ConvertFrom-Json )
Write-Debug "Running Post-Rotation Script on: $ ($Params.userRecordUid) "
# Create a PSCredential to be used to update the Service's `Log On As` property
try {
$Password = ConvertTo-SecureString $Params.newPassword - AsPlainText - Force
$ServiceAccountCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($Params.user), $Password
Write-Debug "New PSCredential created for: $ ($Params.user) "
}
catch {
Write-Error "Failed to create PSCredential for: $ ($Params.user) "
}
$ServiceStatus = Invoke-Command `
- HostName $TargetMachine `
- UserName $SSHUsername `
- ScriptBlock { `
Stop-Service - Name $ Using :ServiceName; `
Set-Service - Name $ Using :ServiceName - Credential $ Using :ServiceAccountCredential; `
Start-Service - Name $ Using :ServiceName; `
return Get-Service $ Using :ServiceName;
}
Write-Debug "$ServiceName is: $ ($ServiceStatus.Status) "