iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🪟

Automatically Re-sign in upon Remote Desktop Session Disconnection

に公開

When operating Windows 11 Pro via Remote Desktop, there are cases where you might want the local machine to automatically sign back in upon session disconnection.
In this article, I handled this by using Task Scheduler to automatically execute an auto-sign-in script when an RDP session is disconnected.


Environment

  • Windows 11 Pro 25H2

Creating the Auto-Sign-in Scripts

Create the following two files and place them in any directory.
When doing so, please remember to replace the username on the first line of RDP2Console.ps1.

RDP2Console.ps1
$username = "【Username】"
$targetLine = query session | Where-Object { $_ -match $username }

if (-not $targetLine) {
    exit 1
}

if ($targetLine -match '.*(\d+).*Disc') {
    $sessionId = [int]$Matches[1]
} else {
    exit 1
}
tscon $sessionId /dest:console
Launcher.bat
@echo off
SET ScriptPath=%~dp0RDP2Console.ps1
powershell.exe -NoLogo -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "%ScriptPath%"

Task Scheduler Settings

  • Launch Task Scheduler.
  • Right-click and select Create Task....
  • Configure the General tab as shown in the image below.
  • Add a new value to the Triggers tab and configure it as shown in the image below.
    • Log: Microsoft-Windows-TerminalServices-LocalSessionManager/Operational
    • Source: TerminalServices-LocalSessionManager
    • Event ID: 24
  • Add a new value to the Actions tab and set it to the Launcher.bat file you prepared earlier.
  • Configure Conditions and Settings as you prefer.


That's all.
If your PC is configured to require a password at startup, you might need to pass the password as an argument when using the tscon command.
In that case, try adding /password:【Password】 to the end of the tscon line.

Discussion