"Session Not Found" Error When Using a Startup Script to Disconnect User Sessions

"Session Not Found" Error When Using a Startup Script to Disconnect User Sessions

Issue Description

When using a startup or logout script to disconnect user sessions on Windows, some users encounter the following error:
WarningSession not found

This usually happens when the username contains spaces, for example:

USER NAME

In such cases, the query user command fails to correctly locate the session, preventing the script from executing as expected.


Solution

To work around the issue caused by spaces in the username, use the wildcard variable %User*Name% instead of %USERNAME%.
This ensures the user session is identified correctly, even when the name contains spaces.

Corrected Script Example
Quotefor /f "skip=1 tokens=3" %%s in ('query user %User*Name%') do (%windir%\System32\tscon.exe %%s /dest:console)

This script performs the following:

  1. query user searches for the session using a wildcarded username.

  2. tscon disconnects the session and redirects it to the console.


Notes

The for /f "skip=1 tokens=3" syntax is used to extract the session ID from the query user output.
Using %User*Name% provides better compatibility for usernames with spaces or special characters.

Conclusion

If your disconnection script fails with a "Session not found" error and the username contains spaces, simply replace %USERNAME% with %User*Name%.
This small change ensures your script functions correctly regardless of the username format