Script to Kill All RDP Sessions - batch-file

I am trying to create a simple script to kill ALL remote desktop sessions, active or disconnected, without rebooting the server. My server OS is Windows Server 2012R2 with Remote Desktop Services enabled and licensed.
I found a simple batch file script here to do this task: enter link description here
When I run this script locally on my terminal server, I get an error in the batch file runs that says: Session Disc not found
And only the console user is logged off. Can anyone tell me what is wrong with this script?
query session >session.txt
for /f "skip=1 tokens=3," %%i in (session.txt) DO logoff %%i
del session.txt
My Session text file looks like this:
SESSIONNAME USERNAME ID STATE TYPE DEVICE
services 0 Disc
>console Administrator 13 Active
wcunningham 18 Disc
kstarkey 25 Disc
rdp-tcp#11 cyannone 52 Active
rdp-tcp 65536 Listen

What I found is a good workaround is adding an additional line to handle the disconnected sessions. Since disconnected sessions don't list the sessionname, the ID is at position 2 not position 3 like it is with active session. So adding an additional line that specifies token=2 did the trick:
query session >session.txt
for /f "skip=1 tokens=2," %%i in (session.txt) DO logoff.exe %%i
for /f "skip=1 tokens=3," %%i in (session.txt) DO logoff.exe %%i
del session.txt

skip the first 3 lignes and the active user
query session >session.txt
for /f "skip=3 eol=> tokens=2," %%i in (session.txt) DO echo %%i
for /f "skip=3 eol=> tokens=3," %%i in (session.txt) DO echo %%i
del session.txt

Related

SC failure command with wildcard

I am trying to write a batch script to configure the recovery options (First failure, second failure, subsequent failure) i.e. SC failure for a custom server installed as a Windows service.
The problem is the Service Name of the Windows service will be different for each installation. The Service Name will be in format ProductName_ServerName_Version where the ProductName and Version will keep changing and ServerName will be constant. So I wanted to find the installed Windows Service and configure the Recovery options via a batch file which I can use for all installations since the ServerName part is constant and I want to lookup using that. I use the below script.
#echo off
set "service=TestSrv"
for /f "tokens=2 delims=: " %%# in ('sc query type^= service^|find /i "SERVICE_NAME:"^|findstr /i /b /c:"SERVICE_NAME: %service%"') do (
set "nservice=%%#"
)
echo %nservice%
sc failure "%nservice%" reset= 60000 actions= restart/60000/restart/60000/restart/60000
Here TestSrv is the ServerName and the above script only returns the Service Name correctly if it is starting with TestSrv. I want a %ServerName% lookup and how to achieve that.
Thanks in Advance.
If you're happy to accept that you will not have any other services within the system which have a name containing _TestSrv_ then you could use WMI to retrieve the service name.
For example, (please change TestSrv on line 1 and complete the last line as necessary):
#Set "ServerName=TestSrv"&Set "nservice="
#For /F Delims^= %%G In ('%__AppDir__%where.exe /R %__AppDir__% mof.xsl 2^>NUL'
)Do #For /F Tokens^=6Delims^=^" %%H In ('%__AppDir__%wbem\WMIC.exe Service^
Where "Name Like '%%[_]%ServerName%[_]%%'" Get Name /Format:"%%G" 2^>NUL'
)Do #Set "nservice=%%H"
#If Not Defined nservice Exit /B 1
#Echo %nservice%
#%__APPDIR__%sc.exe failure "%nservice%" etc…

PSGETSID script to change IE setting

Has anyone made a script to change a registry file based on a users SID remotely?
I'm trying to make IE prompt that it is the default browser - we have PCs that are locked down, but Google Chrome keeps getting installed and it's being set as the default browser and it's causing issues. So an easy fix, rather than logging in as an admin is just to change a simple registry key, open IE, hit yes, and be done. The PCs I am working with are all generic usernames with similar passwords, so I'm trying to make this as easy as possible.
Here's what I have so far
#echo off
ECHO PC Name
SET /P pc=
ECHO.
ECHO Generic Username Logged In
SET /P un=
ECHO.
for /F "usebackq delims== skip=1" %%i in (`\\gtchghost\installs\PSTools\psgetsid.exe \\%pc% \%un%`) do set uSID=%%i
REG ADD "\\%pc%\HKEY_USERS\%%i\Software\Microsoft\Internet Explorer\Main" /v "Check_Associations" /t REG_SZ /d "yes"
pause
I keep getting
ERROR: The parameter is incorrect.
If I run this command I get the SID which is what I am trying to make a variable.
psgetsid \\pc \username

WMIC query to derive absolute share paths on LAN in Windows 10

I'm trying to derive an absolute or full local path from a network path of a folder on a PC drive on LAN using WMIC or similar network tool run from a batch. A few threads devoted to similar tasks on this site when tested don't offer working solution in Win 10.
For example, when running a suggested in one answer query in Win 10 Cmd, I got:
C:\WINDOWS\system32>wmic share where "name='\\Laptop\Data'" get path
Node - OFFICE
ERROR:
Description = Invalid query
C:\WINDOWS\system32>wmic share where "name='Data'" get path
No Instance(s) Available.
I need this result: K:\Data , where K:\ is a hard drive of the remote PC on LAN, and Data is shared folder on that drive.
Can someone suggest a working query & batch for that task? WMIC documentation is way too extensive to derive a working query by trial-and-error without significant experience in using the tool.
wmic share where name='C$' get path
Works here (as only one test doesn't need double quotes). So does
wmic share where "name='C$'" get path
What you posted says you don't have a share called data.
wmic share get /format:list
Shows you what you have.
C:\Users\User>wmic share get
AccessMask AllowMaximum Caption Description InstallDate MaximumAllowed Name Path Status Type
TRUE Remote Admin Remote Admin ADMIN$ C:\Windows OK 2147483648
TRUE Default share Default share C$ C:\ OK 2147483648
TRUE Default share Default share D$ D:\ OK 2147483648
TRUE fred fred C:\Intel OK 0
TRUE Default share Default share G$ G:\ OK 2147483648
TRUE Remote IPC Remote IPC IPC$ OK 2147483651
TRUE TestC TestC C:\ OK 0
As usual wmic /?, wmic share /?, wmic share call /?, wmic share get /?, wmic /format /?.
For remote computers you have to connect to that computer (see wmic /node /?).
wmic /node:127.0.0.1 share get
The following lists the drive letters mapped on the local machine to the (currently connected) remote shares.
C:\etc>for /f "tokens=1-3" %x in ('net use') do #if /i "%x" equ "ok" echo %z = %y
\\laptop\x$ = P:
\\laptop\data = Q:
Following the OP edit (highlight mine):
[+ EDIT for correct net share usage]
I need this result: K:\Data , where K:\ is a hard drive of the remote PC on LAN, and Data is shared folder on that drive.
If you need the K: drive letter assigned on the remote machine to the drive containing the shared directory, then you could run net share remotely using PsExec or similar (provided you have an account with enough rights on the remote machine).
For example, assuming \\laptop is another machine on the LAN, the following will list the share names and (remote) directories on \\laptop.
C:\etc>for /f "tokens=1,2" %u in ('psexec \\laptop cmd /c net share 2^>nul') do #(
for /f "tokens=1,2 delims=:" %x in ("%u %v") do #(
if not "%y"=="" echo "\\laptop\%u" = "%v" ) )
"\\laptop\C$" = "C:\"
"\\laptop\ADMIN$" = "C:\Windows"
"\\laptop\DATA" = "K:\Data"
Suggested in the thread techniques worked with certain additional actions.
When using WMIC, I had to add local admin account to WMI Control Security property. As well, by running GPEDIT.msc enabled "Allow inbound remote administration exceptions" to Firewall rules, despite Firewall was disabled. The proper query is below, processing it's output required a batch file similar in approach to PsExec batch:
wmic /user:[username] /password:[password] /node:"PC-ID" share get
#echo off
setlocal EnableExtensions EnableDelayedExpansion
for /f "tokens=1,2 skip=1 delims=:" %%u in ('wmic /user:[username] /password:[password] /node:"Laptop" share get') do #(
set "var1=%%u" & set "var2=%%v"
set "var1.1=!var1:~89,-1!" & set "var2=!var2:~0,33!" & set "var1.2=!var1:~97!" & set "var1.3=!var1.1:~0,4!"
if not "!var1.3!"=="IPC$" if not "!var1.1!"=="" echo \\Laptop\!var1.1! = !var1.2!:!var2!)
exit /b
::Output
\\Laptop\ADMIN$ = C:\WINDOWS
\\Laptop\C$ = C:\
\\Laptop\D$ = D:\
\\Laptop\Data = K:\
\\Laptop\K$ = K:\
\\Laptop\Docs = K:\Other\Docs
\\Laptop\print$ = C:\windows\system32\spool\drivers
When using PsExec instead of WMIC, I had to install it first, then add an extra key LocalAccountTokenFilterPolicy in Registry, then modify the command posted earlier:
#echo off
for /f "tokens=1,2" %%u in ('psexec64 -u [username] -p [password] \\Laptop cmd /c net share 2^>nul') do #(
for /f "tokens=1,2 delims=:" %%x in ("%%u %%v") do #(
if not "%%y"=="" echo \\Laptop\%%u = %%v ) )
exit /b
::Output
\\Laptop\C$ = C:\
\\Laptop\D$ = D:\
\\Laptop\print$ = C:\windows\system32\spool\drivers
\\Laptop\K$ = K:\
\\Laptop\ADMIN$ = C:\WINDOWS
\\Laptop\Data = K:\
\\Laptop\Docs = K:\Other\Docs

How to create a batch file to map network drives after connected to VPN

What is the best method for creating a batch file (.bat) that will automatically map network drives after a internet connection has been established. The batch file will be remain in the windows start up folder and will only map the network drives if they are not already mapped. I have tried the following:
:Start
ping -n 1 www.google.com
If %errorlevel% == 0 Goto :Start
If %errorlevel% == 1 Goto :Connected
:Connected
Net Use F:\\ Server\Folder /Persistent:No
The ping reply is so fast that the Net use command doesn't map the drive even though the path is correct and will work if I manually enter the net use and path in the CMD window. I need for it to wait after the ping reply and then map the network drives and also for it to only map the network drives if they are not already mapped. I realize what I have tried doesn't address the "only map the network drives if they are not already mapped". I have done some extensive searching and I cannot find the answer to these issues. Would appreciate step by step and easy to follow instructions for resolving this.
Thank you very much.
Maybe additional "timeout" can help?
updated
I use windows vpn client.
To check available connection i make script like this
and wait 30 second before check by ping.
And i ping my server which available only under vpn.
#echo off
set myserver=192.168..
setlocal enabledelayedexpansion
rasdial FirstVPN /disconnect
rasdial SecondVPN /disconnect
echo ==== second vpn
start rasdial SecondVPN
timeout /T 30
for /f "Tokens=*" %%G in ('ping -n 1 %myserver% ^| FIND "TTL="') do set ans="%%G"
IF NOT [%ans%]==[] GOTO Connected
echo ==== first vpn
start rasdial FirstVPN
timeout /T 30
for /f "Tokens=*" %%G in ('ping -n 1 %myserver% ^| FIND "TTL="') do set ans="%%G"
IF [%ans%]==[] (exit)
:Connected
echo %ans%

A bit more challenging - Batch script to add domain user to local administrator group Windows 7

I would like to write a script that will add a domain user to the local administrator group.
I already tried
NET LOCALGROUP Administrators "domain\domainuser" /ADD
but I get the Access Denied error.
The problem is that if I want to run it as domain user, it does not have local admin rights, and if as local admin, it does not have access to the domain names. (I don't want to use domain admin)
If I manually right click the computer icon, than manage, I type in the computer name/local admin user/pass, than in Local Users and Groups -> Groups folder I want to add user to Administrators, I am prompted to log in again. If I log in than with a domain user, it works.
My question is, if it is possible to do the same (or something similar) with batch script?
Maybe, from vbs
GetObject("WinNT://" + WScript.CreateObject("WScript.Network").ComputerName + "/Administrators").Add "WinNT://DomainName/UserName"
I have solved it with another way, using 2 batch files
So I give you my code:
This one creates a folder in c: , than it creates a text file, it copies the name of the current user in it, than the other batch file in the same folder, and finaly runs it as local admin. If you write the password correctly(password will not appear as " * " when you write it):
mkdir c:\tempfiles$
break>c:\tempfiles$\temp.txt
echo %username% >> "c:\tempfiles$\temp.txt"
copy "%~dp0\admin.bat" "c:\tempfiles$"
runas /noprofile /env /user:%computername%\<LOCAL ADMIN USER> "C:\tempfiles$\admin.bat"
pause
rmdir /s /q "c:\tempfiles$"
The admin.bat, takes the user name writen in the text file (if this wasn't, it would take the %username% as the local admin username to add it, because we run it as the local admin)
The copy for the batch file is only necessary so you can run it from anywhere. For example if you would have it on a server's mapped drive it would not work.
set /p u=<c:\tempfiles$\temp.txt
net localgroup Administrators /add <DOMAIN NAME>\%u%
I have tried it on multiple computer, on most of it, it runs. On some of the computers it does not, probably because of the local policy of my company. I did not figgured that out yet.
For any questions or suggestions, feel confident to write your opinion.
The purpose of this batch file is to get the domain group members and add them to a local group. You must right click this file and select Run as Administrator.
#echo off
setlocal EnableDelayedExpansion
set /p v1=[Enter Domain Group Name]
set /p v2=[Enter domain name: xxx.com ]
set /p v3=[Enter Localgroup "Name"]
For /F "skip=8 tokens=1 delims= " %%G IN ('net group %v1% /domain' ) ^
DO if %%G neq The net localgroup %v3% %v2%\%%G /add
timeout /t 1
For /F "skip=8 tokens=2 delims= " %%G IN ('net group %v1% /domain' ) ^
DO if %%G neq command net localgroup %v3% %v2%\%%G /add
timeout /t 1
For /F "skip=8 tokens=3 delims= " %%G IN ('net group %v1% /domain' ) ^
DO if %%G neq completed net localgroup %v3% %v2%\%%G /add
timeout /t 1

Resources