如何使用 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

我的开源项目

相关推荐
非凡ghost2 小时前
Adobe Lightroom安卓版(手机调色软件)绿色版
前端·windows·adobe·智能手机·软件需求
准时准点睡觉3 小时前
window安装MYSQL5.5出错:a windows service with the name MYSQL alreadyexists....
数据库·windows·mysql
喆星时瑜5 小时前
Windows图标修复--缓存重建教程
windows·缓存
0xSec笔记本挖呀瓦呀挖12 小时前
电子取证之windows知识点:从 0 到 1 掌握 Windows 事件日志取证:以 玄机靶场-第五章 Windows 实战-evtx 文件分析
windows
星释15 小时前
鸿蒙Flutter三方库适配指南: 05.使用Windows搭建开发环境
windows·flutter·harmonyos
炒茄子1 天前
Windows:解决电脑开机解锁后黑屏但鼠标可见可移动的问题
windows·计算机外设
luyun0202021 天前
流批了,pdf批量转excel
windows·pdf·excel·figma
vortex51 天前
在 Windows 系统中安装 Oracle、SQL Server(MSSQL)和 MySQL
windows·oracle·sqlserver
路由侠内网穿透1 天前
本地部署开源物联网平台 ThingsBoard 并实现外部访问( Windows 版本)
运维·服务器·windows·物联网·开源
Mr.Lu ‍1 天前
Windows开发,制作开发软件安装程序(二)
windows