Skip to main content

Authenticate to different host

Use case

This script block can be used in combination with an Azure Runbook. For example you can run a PowerShell script on an Active Directory Domain Controller via an AD Joined Hybrid Worker. So, you can use all the advantages of Azure Runbooks with the ability to automate the core of Active Directory. In addition, an external source can dynamically check all AD DCs and scheduled tasks do not have to be manually installed on all domain controllers for the same use case. 

PowerShell Example

This code snippet can be used to authenticate to a host (Server) and use different credentials for the connection. This script is specific to check if the user account in $ServiceAccountUPN has local admin access on the host in $ServerName. To customize the code which will be executed on the remote machine, you have to change the code inside the -ScriptBLock {<insertcustomcodehere>}.

$ServiceAccountUPN = ""
$ServiceAccountPW = ""
$ServerName = ""

$Password = ConvertTo-SecureString -AsPlainText $ServiceAccountPW -Force
$Credential = New-Object System.Management.Automation.PSCredential($ServiceAccountUPN, $Password)

$output = Invoke-Command -Credential $Credential -ComputerName "$ServerName" -ScriptBlock {
    $CurrentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    $isAdmin  = (New-Object Security.Principal.WindowsPrincipal $CurrentUser).IsInRole([Security.Principal.SecurityIdentifier] "S-1-5-32-544")
    write-output "Output $($CurrentUser) ($($isAdmin))"
}

$output

Invoke-Command uses WinRM under the hood. 

WinRM

WinRM uses the Port: 5986 over TCP. In the background is HTTPS Protocol.