powershell - RDP进入具有特定用户名的服务器

标签 powershell arguments rdp start-process

我需要能够调用exe并仅指定服务器名和用户名。我仍然希望它像通常一样提示输入密码。当我调用下面的第一个命令时,RDP会提示我输入密码,但是它已经插入了我的本地用户名。如果要使用其他用户名,则无法在第二个命令中正常使用它。

Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList "/v:$server"

Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList "/v:$server/IP:$username"

如何仅传递服务器名和用户名?

最佳答案

mstsc.exe没有/username参数。但是,它确实有一个/prompt参数,它将提示输入用户名和密码。否则,您需要使用.rdp连接文件。

更新:
您可以利用cmdkey来预加载凭据,因此当您远程访问主机时mstsc不会提示您,然后您自己使用Read-HostGet-Credential等内置功能提示输入凭据。

示例功能:

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
}

可以对其进行修改,以免每次运行时都提示您,因为它将使用cmdkey缓存您的凭据。提示/保存之前,可以使用其他逻辑查询要连接的计算机的cmdkey

这样的例子:
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*'}}
    )

关于powershell - RDP进入具有特定用户名的服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45621098/

相关文章:

azure - RDP 用户 Azure VM

python - 如何以编程方式确定(在 Python 中)何时有人通过 RDP 连接到我的 Windows 7 计算机?

PowerShell 脚本将文件夹上移一级并删除先前包含的文件夹

python - 使用命令行参数在文件中调用 Python 函数

C++ 访问 main 之外的命令行参数?

C++:参数与参数之间的区别?

docker - 通过 GUI 访问 Windows 2016 Server Container(Docker 容器)?

powershell - 对象与哈希表键比较

powershell - 如何使用 powershell 设置 IIS Windows 身份验证提供程序?

azure - 安装 powershell 模块使 Azure Functions 无法正常工作