Today I Learned: 25/09/2021 - Using Powershell Active Directory commands on a remote host via WinRM
I recently developed a small tool to set user passwords on several Active Directory servers via a central Windows bastion host, accessed via WinRM (specifically pywinrm). I ran into a problem using the Active Directory Powershell module via WinRM - commands that worked perfectly when run via the Powershell ISE on the bastion host gave me an access error using WinRM:
Get-ADUser : Unable to contact the server. This may be because this server does not exist, it is currently down, or it does not have the Active Directory Web Services running.
Some Googling suggested the issue was related to credentials not being passed to the AD module via the bastion server. Pywinrm has facilities to forward credentials when using Kereberos, but my authentication is simpler, using NTLM. A variety of config changes could be made on the bastion and target servers to possibly faciliate credential forwarding, but an easier solution was to explicitly pass credentials to the AD module. My username and password for the bastion host were also sufficient to access the AD module, so code like this did the trick. ADMIN_USER and ADMIN_PW are the bastion and AD Module username and password:
$User = "ADMIN_USER" $PWord = ConvertTo-SecureString -String "AMDIN_PW" -AsPlainText -Force $Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User, $PWord Get-ADUser -Server "AD_SERVER" -Credential $Credential USER_TO_QUERY