How to debug task scheduler on win 10? - batch-file

I'm trying to exectute the following bat every 15 minutes on my pc:
#ECHO OFF
SETLOCAL enabledelayedexpansion
SET host=http://dnsad.de/rest/
SET slideshowurl=http://dnsad.de/display/currentSlideshow/mac/
SET slideshowfolder=C:\Slideshow
SET ieprocess="iexplore.exe"
SET ignore_result=INFORMATION:
FOR /f "delims=" %%a IN ('getmac /v ^|find /i "Realtek"') DO (
FOR %%b IN (%%a) DO (
SET element=%%b
IF "!element:~2,1!!element:~5,1!!element:~8,1!"=="---" set mac=%%b
)
)
SET formattedmac=%mac:-=:%
SET macpath=%mac:-=_%
FOR /f "delims=" %%a IN ('curl -X GET %host%%formattedmac%') DO (
FOR %%b IN (%%a) DO (
SET update=%%b
)
)
IF "%update%"=="[true]" (
CD %ProgramFiles%\WinHTTrack\
httrack %slideshowurl%%formattedmac% -q -O "C:\Slideshow" -s0 -B -a
curl -X PUT %host%%formattedmac%
START iexplore -k %slideshowfolder%\dnsad.de\display\currentSlideshow\mac\%macpath%.html
)
EXIT
The script works as it should when executed. Im getting the device's mac address, getting the expected server responses from curl, WinHTTrack is backing up the data correctly, curl updates the server fields and then the internet explorer gets opened with the updated,local html.
When scheduled as Task with win 7 it works as it should as well. When running the bat from Task Scheduler on Win 10 the last thing it does is the curl PUT, but the Internet Exploerer is never opened. The task is marked as succesful.
I am logged in as admin on Win 7 and Win 10. I tested pretty much every setting within the taskscheduler. Nothing seems to be working. Why doesnt the internet explorer start ?
[EDIT]
It seems that the option "Run whether user is logged on or not" causes the problem. But here is the catch:
I'm displaying slideshows in Internet Explorer Kiosk Mode and need to get updated Data from my server to Display new Slideshows regularly. The mentioned option prevents the console from popping up when executing the bat file. If i "only execute if user is logged on" i do get the updated Data to display in Internet Explorer, but every 15 minutes a console window pops up for a second.
I tried exectuing with cmd /c "update" /min "PATH TO BAT" which dosesn't solve the problem.

As mentioned in my [Edit] the problem was the option "run whether user is logged on or not", which i used to prevent the command line window to pop up. When i use the option "only execute if user is logged on" i need to "wrap" the bat in a VBScript which doesnt open the cli. So by scheduling a vbs with the following lines:
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /c PATH\TO\BAT", 0, True
i can execute the bat without a flashing cli.

Related

Batchfile execute only when an RDP session is active

Background:
I have stuff running automatically on my machine that does not work properly when an RDP session is active (it's because of different screen resolutions), and also not when the local machine is locked.
However, I (and several other people) are regularly working on that machine via RDP, but we are prone to forget to close the RDP session, so I created a scheduled task that runs when the PC enters idle mode that closes the RDP session and unlocks the local machine again.
The next problem was: The batch file also runs when there is no RDP connection active.
Using the power of google I found a way of making the batchfile at least quit immediately when the user is only logged in locally.
This is what my batch currently looks like
for /f "tokens=2,4" %%a in ('QUERY USER ^| FINDSTR ">"') DO (
set "consoleTemp=%%a"
set "connectionState=%%b"
set "consoleType=!consoleTemp:~0,7!"
)
SET consoleTypeCorrect=
IF "!consoleType!"=="console" goto closebatch
#echo =================================================
#echo === Remote session is closing in ONE MINUTE ===
#echo =================================================
timeout /t 60 /nobreak
for /f "skip=1 tokens=3" %%s in ('query user %USERNAME%') do (
%windir%\System32\tscon.exe %%s /dest:console
)
Endlocal
Exit
:closebatch
Endlocal
EXIT
The settings for the scheduled task above are like this:
https://imgur.com/a/GMprqvz
Now, this creates another problem: the monitor of the pc stays on, because every time the pc goes idle, the task is run, the batch is executed, which apparently prevents the monitor to go to "sleep".
I have also tried to disable the setting "wake the computer to run this task, but it doesn't change this behavior.
so my main question is: How can I prevent the monitor to remain active when this task is run? or is there an even easier way to achieve the whole thing I want to achieve with this?
This might work...but i've not tested it. At least it may help or give you some ideas.
The section for turning the screen off was taken from this answer https://stackoverflow.com/a/60499680/3004628
#echo off
setlocal enabledelayedexpansion
:: Get local computer SESSIONS info. If find disconnected RDP session, log it off.
:: %%a:SESSIONNAME %%b:USERNAME %%c:SESSIONID %%d:SESSIONSTATE
for /f "tokens=1-4" %%a in ('QUERY session') DO (
set "sessionName=%%a"
set "sessionName=!sessionName:>=!"
if "!sessionName:~0,3!"=="rdp" do (
if /I "%%d"=="Active" do (
set "activeUsers=!activeUsers!%%b, "
) else (
echo Logging of User:%%b
logoff %%c
timeout /t 5 /NOBREAK>
)
) else (
if /I "!sessionName!"=="console" do (
set "consoleID=%%c"
)
)
)
:: If an active console user was detected send a message to their screen.
if defined consoleID (
if defined activeUsers (
msg %consoleID% /W The RDP users "!activeUsers:~0,-2!" are still active. All other RDP sessions have been closed.
) else (
msg %consoleID% /W All other RDP sessions have been closed.
)
)
:: If no active console user detected, run command to turn screen off.
if not defined consoleID (
#Start "" "%__AppDir__%WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -Command "(Add-Type '[DllImport(\"user32.dll\")]public static extern int SendMessage(int hWnd,int hMsg,int wParam,int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)"
)
endlocal
exit /B

How to check if a page is up or if user is connected to the domain

I need some help in regards to a batch scripting. The purpose of the script is to open a web page when the user login into windows.
The web page is hosted into our local servers.
My issue is that the page still open(Obviously it does not display anything) even though the user is not connected to the network.
Unfortunately Ping is restricted. I am trying to either check if the webpage is accessible or if the user is connected to the network in order to launch the page.
Any ideas?
thanks & regards
Found below script that is doing the job.
#set #x=0 /*
:: ChkHTTP.cmd
#echo off
setlocal
set "URL=http://10.0.0.23:8090/FeedBack/index.php"
cscript /nologo /e:jscript "%~f0" %URL% | find "200" > nul
if %ErrorLevel% EQU 0 (
start "" "C:\Program Files\Internet Explorer\iexplore.exe" -k ""http://10.0.0.23:8090/FeedBack/index.php""
) else (
echo
EXIT
)
goto :EOF
JScript */
var x=new ActiveXObject("Microsoft.XMLHTTP");
x.open("GET",WSH.Arguments(0));x.send();
while (x.ReadyState!=4) {WSH.Sleep(1)};
WSH.Echo(x.status)

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

batch FOR loop piped command

Basically I'm trying to read from a text file of servers, ping them continuously, and output a timestamp when each server has rebooted (find "Request timed out.")
for /f "delims=" %%a in (Servers_List.txt) do (
start cmd /k ping -t %%a | find "Request timed out."
) && (Echo %%a rebooted at %time%.)
It launches each server ping -t in a separate window until I add the | find piece, and then it only launches one at a time after each subsequent window is closed.
Does anyone know a way to run each CMD window simultaneously without needing to close each prior window?
Thank you!
Your design cannot work :-(
Your first problem is you are piping the output of your START command, but you want to pipe the output of PING. That can be fixed by escaping the pipe as ^|.
You have a similar problem with your conditional command concatenation - you would need ^&^& instead of &&1.
But the biggest problem is your ECHO will not execute until the pipe is closed, which is never! FIND will continue to look for additional timeout lines after the first one is detected. It will not end until after the pipe is closed, and your ECHO will not run until after FIND terminates.
Your best bet would be to write a VBScript, or JScript, or PowerShell script to continuously ping a server, and write out your message with timestamp when timeout is detected.
You could write a batch script to loop through your list of servers and start a new custom ping process for each one. Or you could put everything into a single VBScript (or JScript, or Powershell) script.
Perhaps one of the following links can help get you started:
http://windowsitpro.com/scripting/how-can-i-use-vbscript-script-ping-machine
http://www.sems.org/2013/07/little-vbscript-to-continously-ping-a-host-with-timestamplog/
https://thwack.solarwinds.com/docs/DOC-135033
I am assuming you ideally would like to have all output in a single screen. You can use the START /B option to run multiple processes within the same console window, but then you run the risk of garbled output if two processes attempt to write to the console at the same time. This can be solved via the exclusive lock that is obtained when a process opens a file for writing. See How do you have shared log files under Windows? for some pointers on how this can help. That link is for shared log files, but it is easily adapted for shared console access.
I have used my JREPL.BAT utility to hack up a solution. Architecturally this is a convoluted abomination, but it works! It runs an endless PING process for each server, all in parallel within the same console. Each process pipes its output to JREPL which detects if the server responded and writes out a time-stamped message to both the console and a log file. The log file is also used as a lock file to coordinated shared access between the processes. Each process keeps track of the last server status, and a message is only written when the status changes.
#if (#X)==(#Y) #end /* Harmless hybrid line that begins a JScript comment
::***** Batch code *******
#echo off
setlocal enableDelayedExpansion
set "first="
copy nul serverStatus.log >nul
for /f "delims=" %%A in (Servers_List.txt) do if not defined first (
set "first=%%A"
) else (
start /b cmd /c ping -t %%A ^| jrepl "^Request timed out|^Reply from " "log('%%A','DOWN')|log('%%A','UP')" /t "|" /jmatch /jlib "%~f0"
)
if defined first ping -t %first% | jrepl "^Request timed out|^Reply from " "log('%first%','DOWN')|log('%first%','UP')" /t "|" /jmatch /a /jlib "%~f0"
exit /b
****** JScript code ******/
var status = 'initial';
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file;
function log( server, newStatus ) {
if (status!=newStatus) {
status=newStatus;
var msg=new Date().toString()+' '+server+' is '+newStatus;
while (!openFile());
file.WriteLine(msg);
output.WriteLine(msg);
file.Close();
}
return false;
}
function openFile() {
try {
file = fso.OpenTextFile('serverStatus.log',8);
return true;
} catch(e) {
return false;
}
}
But, I don't see why it is necessary to run the processes in parallel. It seems to me you can simply enter an endless loop that cycles through the servers, and PINGs each server individually, writing out the status. Here is a simple batch script that does just that. Again, it only prints out a message when it detects a change in status.
#echo off
setlocal enableDelayedExpansion
for /l %%N in () do for /f "delims=" %%S in (Servers_List.txt) do (
ping /n 1 %%S | findstr /bc:"Request timed out" >nul && set "status='DOWN'" || SET "status=UP"
if "!status!" neq "!%%S!" (
set "%%S=!status!"
echo !date! !time! %%S is !status!
)
)

Anyway to reset svn cached auths for a specific repo?

I've been searching all over for this and I'm surprised I haven't found it yet.
I'm using Windows 7.
I've got TortoiseSVN 1.8 with command line tools available but if there is a solution using another client that will work, I'm open to other options.
I'm trying to reset the cached auths for a specific repository on an svn client.
I've have a group of projects (~15) that get built all together. We have setup batch files using the svn command line client to checkout and build the projects which work great on the individual developers machine since the svn client caches their credentials.
However, we are setting up a central build machine for releases (instead of having one person responsible for release builds) and we would like for anyone to be able to login and run a build using their own credentials.
The problem we have is that if we leave the svn client using it's default settings, then anyone logging into the machine will use the previous person's credentials. If we switch the svn client to not cache credentials, then the build process (its all scripted remember) has to prompt for every project which results in the user typing their password ~15 times just to do a build.
We are part of a large company and our svn server houses a lot of different repos for other teams and some developers use multiple repos so I cannot simply clear the cache directory after the build because that would wipe out all cached repos instead of just ours (as far as I can tell, svn only caches by server, not by repo).
Is there any solution I can implement that will prompt for svn credentials on the first project that gets pulled from svn in the batch file, uses those credentials for all projects in the script but then clears the cached credentials for only those projects (or the whole repo) when the script finishes?
I've tried several different method to try and "reset" the credentials for a specific project but I am not having any luck. Even if my script has to go reset them individually, that would be ok.
Someone on another so thread suggested using svn switch on the project and providing a different user via --username when done but that doesn't seem to work on windows (they were using OSX). The next time I run the script, it simply defaults to the last authenticated user.
-edit- added a dumbed down version of the script:
#ECHO OFF
pushd %~dp0
SET SVN=https://domain.com:81/svn/repo
SET TAG=%1
CALL :GET_PROJECT_TAG project1
CALL :GET_PROJECT_TAG project2
CALL :GET_PROJECT_TAG project3
CALL :GET_PROJECT_TAG project4
CALL :GET_PROJECT_TAG project5
CALL :GET_PROJECT_TAG project6
GOTO :END
:GET_PROJECT_TAG
svn export %SVN%/%1/tags/%TAG%/ %TAG%/%1/
EXIT /B
:END
popd
PAUSE
-end edit-
thoughts?
What about having the batch script prompt for credentials if not defined? Use setlocal just below #echo off to make the script forget the credentials on exit. If you'd like to mask the input of the password, it can be done with a PowerShell command.
<NUL set /P "=Password? "
set "psCommand=powershell -command "$p=read-host -AsSecureString;^
$m=[System.Runtime.InteropServices.Marshal];$m::PtrToStringAuto($m::SecureStringToBSTR($p))""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set "pass=%%p"
echo You entered %pass%
Then just reuse %pass% in all svn commands as needed for as long as the script is running. If you're prompted for auth info via a GUI, then might using Subversion for Windows instead of TortoiseSVN solve your problems?
Edit: I feel I should note that it's not unreasonable to expect special characters in passwords that could potentially break your script. Whenever you retrieve the %pass% variable, you should probably do so in the delayed expansion style to prevent characters like ^ and < from being evaluated. But don't enable delayed expansion until retrieval. If delayed expansion is enabled during the input, exclamation marks might be stripped. Do it like this:
#echo off
setlocal
<NUL set /P "=Password? "
set "psCommand=powershell -command "$p=read-host -AsSecureString;^
$m=[System.Runtime.InteropServices.Marshal];$m::PtrToStringAuto($m::SecureStringToBSTR($p))""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set "pass=%%p"
setlocal enabledelayedexpansion
echo You entered !pass!
endlocal
Here are a couple of batch files that I use to temporarily clear the cached credentials. You could easily modify them to suit your particular needs.
:: ClearCachedCredentials.bat
:: 2015-10-30 Kurt Schultz - Tested on Windows 7, 64-bit
:: Move the current TortoiseSVN credential cache files to a backup folder.
:: This allows you to log on to Subversion using a different set of credentials.
:: The original credentials can be restored by running RestoreCachedCredentials.bat
::
:: Alternatively, you can open the individual files in the svn.simple folder using
:: a text editor and look for the user ID that you want to remove from the cache.
:: Remove or delete the file as needed.
#set filePath=\Users\%username%\Application Data\Subversion\auth
#set fileCount=0
#If not exist "C:%filePath%" (
#echo Cannot locate "C:%filePath%"
#echo Do you have Tortoise SVN installed?
) Else (
#C:
#CD "%filePath%"
#for /f %%A in ('dir /b /a-d "svn.simple\*" 2^>nul ^| find /v /c "" ') do #set /a fileCount+=%%A
#Rem When the dir command is issued from the command line, there must be a space between the carat and the pipe e.g. ^ |
#Rem or you will get an error, invalid switch - "v". When inside the "for" command, the space cannot be there.
)
:: I had to move the following section out of the section above in order to test the value of fileCount.
:: When it was inside the Else block above, the value was always 0.
#If %fileCount%==0 (
#echo There were no cached files to backup or clear.
) Else (
#dir svn.simple
#echo.
#echo These credentials will be moved to the backup folder.
#echo.
#echo Press Ctrl-C now to abort or
#pause
)
:: I had to move the following section out of the section above and into its own If condition
:: in order to get the Ctrl-C to work correctly. (The file move did not occur, but the echo
:: statements were still executed.
#If Not %fileCount%==0 (
#If not exist backup (
#md backup
)
#If not exist backup\svn.simple (
#md backup\svn.simple
)
#move svn.simple\*.* backup\svn.simple
#echo.
#echo The TortoiseSVN credentials have been backed up and cleared.
#echo Run RestoreCachedCredentials.bat to restore them.
)
#echo.
#pause
:: RestoreCachedCredentials.bat
:: 2015-10-30 Kurt Schultz - Tested on Windows 7, 64-bit
:: Restore the TortoiseSVN credential cache files from the backup folder.
#set continue=false
#set filePath=\Users\%username%\Application Data\Subversion\auth
#If not exist "C:%filePath%" (
#echo Cannot locate "C:%filePath%"
#echo Do you have Tortoise SVN installed?
) Else (
#C:
#CD "%filePath%"
#If not exist backup\svn.simple (
#Echo The backup directory does not exist. There is nothing to restore.
#Echo You must first use ClearCachedCredentials.bat to create a backup.
) Else (
#echo This will restore the Subversion credentials from your backup folder.
#echo Press Ctrl-C now to abort or
#pause
#set continue=true
)
)
#If %continue%==true (
#copy backup\svn.simple\*.* svn.simple
#echo.
#echo The TortoiseSVN credentials have been restored.
)
#echo.
#pause

Resources