The simplest way to setup credentials for another user remotely using cmdkey
, is to create a scheduled task, that is run under the user account for which you want to add the credentails via cmdkey
.
Connect to the machine in question using an admin account via Enter-PSSession -ComputerName target_machine
(or run the commands via Invoke-Command
).
With SeBatchLogonRight
already set
If the user account for which you want to add credentials via cmdkey
already has the SeBatchLogonRight
set (usually only admins), then it is fairly simple:
$job = Register-ScheduledJob -ScriptBlock {
cmdkey /add:target_machine:target_port /user:target_domain\target_user /pass:target_user_password
} -Name "Add user credentials" -Credential (New-Object System.Management.Automation.PSCredential("source_domain\source_user", (ConvertTo-SecureString "source_user_password" -AsPlainText -Force))) -RunNow
Unregister-ScheduledJob -InputObject $job
Without SeBatchLogonRight
already set
If the user account for which you want to add credentials via cmdkey
does not have the SeBatchLogonRight
set already, then you need to (temporarily) grant it the right. A simple way to do this remotely is to use the PowerShell module from Tony Pombo (the original ScriptCenter location is not available anymore, so this script now uses a mirror on a public GitHub repo):
Invoke-WebRequest https://raw.githubusercontent.com/MightyCrizo/cis-microsoft-windows-server-2016-benchmark-powershell/4294a356825a10afacf7da3969ba2f5edf761b21/UserRights.psm1 -OutFile UserRights.psm1
# You might need to setup at least the following execution policy, if you haven't already:
# Set-ExecutionPolicy AllSigned
Import-Module .\UserRights.psm1
Grant-UserRight -Account "source_machine\source_user" -Right SeBatchLogonRight
$job = Register-ScheduledJob -ScriptBlock {
cmdkey /add:target_machine:target_port /user:target_domain\target_user /pass:target_user_password
} -Name "Add user credentials" -Credential (New-Object System.Management.Automation.PSCredential("source_domain\source_user", (ConvertTo-SecureString "source_user_password" -AsPlainText -Force))) -RunNow
Unregister-ScheduledJob -InputObject $job
Revoke-UserRight -Account "source_machine\source_user" -Right SeBatchLogonRight
The following placeholders have been used in the scripts above:
source_domain
= The domain source_user
belongs to.
source_user
= The user for which the cmdkey
command will be executed (cmdkey
runs in this user's context).
source_user_password
= The password of the source_user
account.
target_machine
= The target computer used in the cmdkey
command.
target_port
= The target port used in the cmdkey
command (optional). (E.g. use 1433
for Windows Authentication in conjunction with SQL Server.)
target_domain
= The domain target_user
belongs to.
target_user
= The target user account used in the cmdkey
command. source_user
will impersonate this user, when connected to target_machine
.
target_user_password
= The password of the target_user
account.