mstsc.exe
does not have a /username
parameter. It does, however, have a /prompt
argument which will prompt for username and password. Otherwise, you need to use a .rdp
connection file.
Update:
You can utilize cmdkey
to preload credentials so mstsc
does not prompt you when you remote into a host, and then prompt for credentials using built-in functionality such as Read-Host
or Get-Credential
yourself.
Example function:
function Connect-Host
{
param
(
[Parameter(Position = 0, Mandatory)]
[ValidateScript({Test-Connection -ComputerName $PSItem -Quiet})]
[string]
$ComputerName,
[Parameter(Position = 1)]
[System.Management.Automation.CredentialAttribute()]
[pscredential]
$Credential = (Get-Credential)
)
$cmdKeyArgs = @(
"/generic:TERMSRV/$ComputerName"
"/user:$($Credential.UserName)"
"/pass:$($Credential.GetNetworkCredential().Password)"
)
$null = & "$Env:SystemRoot\System32\CMDKEY.exe" @cmdKeyArgs
& "$Env:SystemRoot\System32\MSTSC.exe" /v:$ComputerName
}
This can be modified so it doesn't prompt you every time you run it since it will cache your credentials with cmdkey
. Additional logic can be used to query cmdkey
for the computer you're connecting to prior to prompting/saving.
Example of this:
cmdkey /list |
Select-String -Pattern $ComputerName -Context 2 |
Select-Object -Property @(
@{N='ComputerName';E={$ComputerName}}
@{N='User';E={$PSItem.Context.PostContext[-1] -replace '\s*User:\s*'}}
)