如何使用 PowerShell 自动登录远程桌面 ?

在快节奏的 IT 世界和远程工作中,效率和节省时间的技术是最重要的。对于经常连接到远程桌面的专业人员来说,手动输入登录凭据的过程可能是一项乏味且耗时的任务。为了应对这一挑战,PowerShell 脚本提供了一种自动登录远程桌面连接的解决方案,从而节省了时间并提高了生产力。

The PowerShell Script

下文中提供的 PowerShell 脚本演示了自动登录到远程桌面连接 (RDC) 的过程。它巧妙地利用了一系列 cmdlet 命令来简化身份验证过程,使用户能够连接到远程桌面,而无需每次都手动输入凭据。

powershell 复制代码
## PowerShell Script to auto login to remote desktop

# Set variables for server address, username, and password
# Keep password in single quote to handle special character
$Server = "rdc.example.com"
$User = "username"
$Password = 'password'

# Remove any existing Remote Desktop Connection credentials from Windows Credential Manager
cmdkey /list | ForEach-Object {
    if ($_ -like "*target=TERMSRV/*") {
        $credentialTarget = $_ -replace " ", "" -replace "Target:", ""
        cmdkey /del:$credentialTarget
    }
}

# Announce the initiation of a connection to the specified Remote Desktop
echo "Connecting to $Server"

# Save the Remote Desktop connection credentials using cmdkey
cmdkey /generic:TERMSRV/$Server /user:$User /pass:$Password

# Initiate a Remote Desktop connection to the specified server
mstsc /v:$Server

How the Script Works

Setting Up Connection Parameters

第一步是配置远程桌面系统主机地址和登录凭据。

powershell 复制代码
$Server="rdc.example.com"
$User="username"
$Password='password'

Clearing Existing Credentials

然后,代码开始使用 cmdkey 列出所有保存的凭据,然后筛选出远程桌面的凭据,使用模式"target=TERMSRV/"进行连接。然后删除这些凭据,以确保使用新的登录信息。

powershell 复制代码
cmdkey /list | ForEach-Object{
    if($_ -like "*target=TERMSRV/*"){
        cmdkey /del:($_ -replace " ","" -replace "Target:","")
    }
}

Shows a message

脚本在屏幕上打印一条消息,表明与远程桌面的连接已启动。

powershell 复制代码
# Announce the initiation of a connection to the specified Remote Desktop
echo "Connecting to $Server"

Saving Credentials

脚本使用 cmdkey 为远程桌面服务器创建通用凭据项。此步骤保存用户名和密码,使自动化登录更高效。

powershell 复制代码
cmdkey /generic:TERMSRV/$Server /user:$User /pass:$Password

Initiating the Remote Desktop Connection

最后,脚本调用 MSTSC,启动连接到远程桌面。

powershell 复制代码
mstsc /v:$Server

Implementation Steps

脚本使用步骤如下:

(1) 将上述脚本保存为 connect remote desktop.ps1

(2) 替换实际的远程桌面服务器地址、用户名和密码。

(3) 在脚本上右键单击,然后选择 Run with PowerShell

我的开源项目

相关推荐
CyrusCJA20 分钟前
在Windows系统上将Redis注册为系统服务使其实现开机自启
数据库·windows·redis·缓存
星辰徐哥3 小时前
OpenCV入门:Windows系统下OpenCV的安装与环境配置
人工智能·windows·opencv
love530love3 小时前
Clink 在 VS 2022 Developer Command Prompt 中的配置与路径精简调校
人工智能·windows·microsoft·clink
charlie1145141913 小时前
通用GUI编程技术——图形渲染实战(三十六)——Constant Buffer与数据传递:CPU-GPU通信通道
开发语言·c++·windows·c·图形渲染·win32
少控科技4 小时前
小数典应用:小诗典
windows·c#
hjhcos5 小时前
【Hermes】Windows通过WSL的Ubuntu安装部署Hermes并配置飞书
windows·ubuntu·飞书
梦幻通灵5 小时前
window操作系统中系统文件或映像文件的修复实用命令
windows·系统安全
XLYcmy5 小时前
2026游戏安全技术竞赛-PC客户端安全-初赛 求解起点到终点的最短路径
windows·python·网络安全·dfs·bfs·游戏安全·曼哈顿距离
一个人旅程~5 小时前
ARM版的windows(macbook虚拟机使用)在国内外技术平台有哪些版本可以选择?
windows·经验分享·macos·电脑
x***r1516 小时前
vcredist_x64安装步骤详解(附VC++运行库缺失解决方法)
windows