Showing posts with label cmd. Show all posts
Showing posts with label cmd. Show all posts

2018-06-14

Disable High Contrast Mode Windows 10

This is a script we use to disable High Contrast Theme during logon/logoff.
The problem was that some students set High contrast theme, either by choice or by accident and then the settings applied to the lock screen after they logged off, and then the next user got the setting and so on. UEV helped to spread this like a virus in our student computer rooms.

This is the solution!

In your logon and logoff script, run this:

::=== SCRIPT BEGINS ===
:: Set default Theme if High contrast mode is enabled
FOR /f "skip=2 tokens=3 delims= " %%A IN ('REG QUERY "HKEY_CURRENT_USER\Control Panel\Accessibility\HighContrast" /v Flags') do (
SET "reg_value=%%A"
)

IF "%reg_value%" EQU "127" (
C:\Windows\resources\Themes\aero.theme
taskkill /F /IM systemsettings.exe
)
::=== SCRIPT ENDS ===


You can also run this in powershell as a scheduled task running as the logged on user during logon/logoff. But for some reason it did not work every time for me, so I had to go for the logon-script version.


#=== SCRIPT BEGINS ===
# Set this to 1 for visual outputs of variables
$DEBUG = 0
# Set this to SilentlyContinue for no debug, or Continue for debug output
IF ($DEBUG -eq 1) {
    $DebugPreference = "Continue"
} else {
    $DebugPreference = "SilentlyContinue"
    #$DebugPreference = "Continue" # This one is used for debuging debug mode ;)
}

$HighContrastFlags = (Get-ItemProperty 'HKCU:\Control Panel\Accessibility\HighContrast' -Name "Flags").Flags
Write-Debug "`$HighContrastFlags is $HighContrastFlags"

# 127 is High contrast theme, 126 is not high contrast. 
IF ($DEBUG -eq 1) {
    $CheckValue = 126
} Else {
    $CheckValue = 127
}
IF ($HighContrastFlags -eq $CheckValue) {
    Write-Debug "`$HighContrastFlags equals `$CheckValue"
    & $ENV:SYSTEMROOT\resources\Themes\aero.theme
    # Loop ultil file exist or counter is tripped
    $loopCounter = 0
    while (!(Get-Process -ProcessName SystemSettings -ErrorAction Ignore) -and $loopCounter -lt 30) { 
        $loopCounter++
        Start-Sleep 2
        Write-Debug "Loopcounter is $loopCounter"
    }
    Stop-Process -ProcessName SystemSettings -Force
} Else {
    Write-Debug "`$HighContrastFlags does not equal `$CheckValue, script should not run"
}
#=== SCRIPT ENDS ===

2017-01-28

checkfreediskspacemsg.cmd

Why I created the script

I needed a script that could notify users about their hard drive having to little free disk space. Many of our users didn't know or care about this and it became a problem when software updates could not become installed (many of them use laptops and are travelling a lot, so we could not force them to use file server storage).

What is does

When you run the script you provide it with the amount of needed disk space in GB and in %. If the free disk space is lower than either of these values, the script will send a message to the logged on user.
At the moment I only care about the system drive.


For this picture I set very high requirements to get the msg (100GB or 80% free)

How I run it

I run this script as a scheduled task that runs on a 30 second logon delay and every hour when a user is logged on. It also runs as the logged on user to make sure the script can sent the MSG as the user to the user. To avoid the black cmd screen from popping up, I launch it with the invisible.vbs script.

The script

@ECHO OFF
:: Script get data from input and returns 0 if conditions met.
:: davpe67 2016-02-11
IF "%~1" == "" GOTO :SYNTAX
IF "%~2" == "" GOTO :SYNTAX

SET GBNEEDED=%~1
SET PERCENTNEEDED=%~2
SET TIMEOUT=%~3
IF "%~3" == "" SET TIMEOUT=1440

SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "tokens=1-3" %%n IN ('WMIC LOGICALDISK GET Name^,Size^,FreeSpace^|findstr /i "c:"') DO (
 SET FreeBytes=%%n
 SET TotalBytes=%%p
)
SET /A TotalSpace=!TotalBytes:~0,-9! 
SET /A FreeSpace=!FreeBytes:~0,-9!
SET /A TotalUsed=%TotalSpace% - %FreeSpace%
SET /A PercentUsed=(!TotalUsed!*100)/!TotalSpace!
SET /A PercentFree=100-!PercentUsed!
::ECHO Total space: %TotalSpace%GB
::ECHO Free space: %FreeSpace%GB
::ECHO Used space: %TotalUsed%GB
::ECHO Percent Used: %PercentUsed%%%
::ECHO Percent Free: %PercentFree%%%

IF %FREESPACE% LSS %GBNEEDED% SET NEEDMOREDISK=1
IF %PERCENTFREE% LSS %PERCENTNEEDED% SET NEEDMOREDISK=1


IF "%NEEDMOREDISK%" == "1" (
 ECHO %COMPUTERNAME% is running low on diskspace on C: ^(%FREESPACE%GB ^/ %PERCENTFREE%%%^)>%TEMP%\msgfile.tmp
 ECHO If there is not enough free space the computer will become slow >>%TEMP%\msgfile.tmp
 ECHO becuse it needs more time to find sectors to write the data.>>%TEMP%\msgfile.tmp
 ECHO A golden rule is that at least 10%% and^/or 10GB ^(whatever is biggest^)>>%TEMP%\msgfile.tmp
 ECHO of free space is needed by workstations.>>%TEMP%\msgfile.tmp
 ECHO.>>%TEMP%\msgfile.tmp
 ECHO Some programs wont install or upgrade ^(old versions may be removed^)>>%TEMP%\msgfile.tmp
 ECHO until you have cleared at least %GBNEEDED%GB and^/or %PERCENTNEEDED%%%.>>%TEMP%\msgfile.tmp
 ECHO.>>%TEMP%\msgfile.tmp
 ECHO Most users have way more data stored locally than they need to.>>%TEMP%\msgfile.tmp
 ECHO Move files you are not working with to the home- or nobackup-server.>>%TEMP%\msgfile.tmp
 ECHO If you need help to make more space, contact support@yourcompany.com>>%TEMP%\msgfile.tmp
 MSG %USERNAME% /TIME:%TIMEOUT%<%TEMP%\msgfile.tmp
 EXIT /B 911
)

EXIT /B 0
GOTO :EOF
:SYNTAX
ECHO.
ECHO %~nx0 ^<GBNEEDED^> ^<PERCENTNEEDED^> ^<TIMEOUT^>
ECHO.
ECHO GBNEEDED is number of GB och free disk needed
ECHO PERCENTNEEDED is how many percent of total disk need to be free
ECHO TIMEOUT is how long the user message will remain on the screen


2016-11-28

Network lag & packet loss checker script

Why I created the script

At the time I had experienced a lot of strange packet loss and lag on my Internet connection at home. And as you all know, when you call the ISP support they just blame EVERYTHING on your home router. I needed a way to monitor and log the packet loss and I started to write the script networkcheck.cmd. To begin with I used my own routers IP, the gateway of the ISP and two other stable web sites. That way I could prove to them that I didnt have packet loss "on my side".

What is does

The script detects network lag and packet loss. Its not very advanced but it have helped me to detect network anomalies at several occasions.  Make sure you read through the script before you run it. I have flagged some parts with Check_Before_Run so you can find them easily.

If everything is fine you wont see anything but if things are not ok...
The first check is to see if the gateway is responding. If not you will get an output that looks like this:

The next check is a nslookup of the pre-set domains to see that domain can be resolved:
 And if the request times out:
The text should say PING error, it was a typo.
If any of the above problems are detected, the script will halt.
When gateway and DNS is working the script will ping all the hosts to scan for packet loss:
 If no packet loss is detected but the average response time is too high:
 

How I run it

I run the script as a scheduled task in Windows as the current logged in user. (you probably want to use invisible.vbs to launch the cmd script to avoid cmd black screen popups every time it runs)

Make sure you don't run the script as the SYSTEM or it will halt. This is because the MSG cannot send to a user if run as SYSTEM.


The script must be run as the logged on user. Add the "Users" group to the "use the following user account".

Add a schedule of your choice. I make mine rune every hour with a 30 min random delay.
When I detect problems I change the schedule to run every 15 minutes.

Add the wscript.exe to the program path

Then add the path to the invisible.vbs followed by the path to the networkcheck.cmd as optional arguments.

The script

:: networkcheck.cmd
:: Network check and alert thingy by david.djerf@liu.se 2013-10-10 11:11
:: Part of script copy pasted from scripts found on the Internet
:: It have been very tricky to test the script since network problems are hard to simulate. Please let me know if somthing isnt working properly!
:: 2013-10-01 Added check for games to avoid unwanted alt+tab to desktop while playing
:: 2014-03-26 Fixed broken DNS check when DNS is failing
:: 2014-07-10 Adding traceroute if packetloss
:: 2016-11-27 Made some changes to work properly with Windows 10
::      Made script halt if DNS or PING errors detected
::     New way to set current date and time to work with different date formats
::     Added checks for the log folder to make sure it exists and is writable
::     Added check to see if script is already running (needed when started by invisible.vbs as scheduled task)
::     Added a lot of comments 
:: 2017-01-16 Added some checks to detect if Internet is not reachable (to speed up error msg and abort script)


@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET DEBUG=0

:: Check_Before_Run
:: Don't check if program x is running
::tasklist |findstr /i "program.exe">NUL
::IF "%ERRORLEVEL%" == "0" GOTO :EOF

:: Don't check if Cisco VPN is running
tasklist |findstr /i "vpnui.exe">NUL
IF "%ERRORLEVEL%" == "0" GOTO :EOF

:: Checkroute IP - Set this to something that is trusted to be online outside your network.
:: Check_Before_Run
SET CHECKROUTEIP=x.x.x.x

:: Hosts to ping. Make sure you choose hosts with stable latency and benchmark them before you set the LATENCY variable value below
:: Check_Before_Run
SET PINGHOST1=changeme1.com
SET PINGHOST2=changeme2.com
SET PINGHOST3=changeme3.com
SET PINGHOST4=changeme4.com
:: Number of pings - Warning Dont set this to low as the avrage values will become unpredictable
SET NUMPINGS=30
:: Acceptable average latency in ms
SET LATENCY=12


:: Reset variables used later
SET PINGHOSTLAG=0
SET LAG=0
SET LOSS=0
SET HALT=0
SET GATEWAY=
SET MSGUSER=
SET IP=
:: where to log and make sure it is writable
SET LOGPATH=%~dp0\logs
IF NOT EXIST "%LOGPATH%" MKDIR "%LOGPATH%" >NUL 2>&1
IF NOT EXIST "%LOGPATH%" (
 ECHO Could not create %LOGPATH%
 SET HALT=1
)

IF EXIST "%LOGPATH%\writetest.tmp" DEL /F "%LOGPATH%\writetest.tmp"
IF EXIST "%LOGPATH%" ECHO Write test>"%LOGPATH%\writetest.tmp" 2>NUL
IF NOT EXIST "%LOGPATH%\writetest.tmp" (
 ECHO Could not write to %LOGPATH%
 SET HALT=1
)

for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' SET ldt=%%j
SET YEAR=%ldt:~0,4%
SET MONTH=%ldt:~4,2%
SET DAY=%ldt:~6,2%
SET HOUR=%ldt:~8,2%
SET MINUTE=%ldt:~10,2%
SET SECOND=%ldt:~12,2%


:: Make sure script is not running already, reset if lock file is old
IF EXIST "%LOGPATH%\_lock.tmp" (
 FINDSTR /i "%YEAR%-%MONTH%-%DAY%" "%LOGPATH%\_lock.tmp">NUL 2>&1
 IF NOT "%ERRORLEVEL%" == "0" ( 
  DEL /F "%LOGPATH%\_lock.tmp"
 ) ELSE (
  TYPE "%LOGPATH%\_lock.tmp"
  GOTO :EOF
 )
)

ECHO Script is running %YEAR%-%MONTH%-%DAY% %HOUR%:%MINUTE%:%SECOND%>"%LOGPATH%\_lock.tmp"
IF "%HALT%" == "1" CALL :CLEANUP && EXIT /B 911

:: Automatically find  gateway
FOR /f "tokens=1-2 delims=:" %%A IN ('IPCONFIG^|findstr /i "default.gateway"') DO IF NOT DEFINED GATEWAY SET GATEWAY=%%B
:: Remove space
SET GATEWAY=%GATEWAY:~1%
SET MSGUSER=%USERNAME%
IF "%MSGUSER%" == "%COMPUTERNAME%$" (
 ECHO Script cannot send MSG if run as SYSTEM
 CALL :CLEANUP
 EXIT /B 99
)

FOR /f "tokens=1-2 delims=:" %%A IN ('IPCONFIG^|findstr /i "IPv4.address"') DO IF NOT DEFINED IP SET IP=%%B
SET IP=%IP:~1%

:: Check_Before_Run
:: If script is to be run by scheduled task as SYSTEM user you must set MSGUSER
:: Set GATEWAY to IP or dns-name
:: local user to send warnings to, if script is run by the current user set MSGUSER=%USERNAME%
ECHO %IP%| FINDSTR /I "192.168.10" >NUL 2>&1
IF "%ERRORLEVEL%" == "0" (
 SET GATEWAY=192.168.10.1
 SET MSGUSER=artoo
)
ECHO %IP%| FINDSTR /I "130.236.168.211" >NUL 2>&1
IF "%ERRORLEVEL%" == "0" (
 SET GATEWAY=liunet-gw.ifm.liu.se
 SET MSGUSER=administrator
)
ECHO %IP%| FINDSTR /I "192.168.98" >NUL 2>&1
IF "%ERRORLEVEL%" == "0" (
 SET GATEWAY=liunet-gw.ifm.liu.se
 SET MSGUSER=administrator
)

:: Failsafe
IF "%GATEWAY%" == "" CALL :CLEANUP && EXIT /B 911
IF "%MSGUSER%" == "" CALL :CLEANUP && EXIT /B 911


:: *** BEGIN DO STUFF ***
CALL :CHECKGATEWAY
IF "%HALT%" == "1" CALL :CLEANUP && EXIT /B 911
CALL :CHECKROUTE
IF "%HALT%" == "1" CALL :CLEANUP && EXIT /B 911
FOR %%A in (%PINGHOST1% %PINGHOST2% %PINGHOST3% %PINGHOST4%) DO SET PINGHOST=%%A&& CALL :CHECKDNS
IF "%HALT%" == "1" CALL :CLEANUP && EXIT /B 911
FOR %%A in (%PINGHOST1% %PINGHOST2% %PINGHOST3% %PINGHOST4%) DO SET PINGHOST=%%A&& CALL :PING
IF "%HALT%" == "1" CALL :CLEANUP && EXIT /B 911
FOR %%A in (%PINGHOST1% %PINGHOST2% %PINGHOST3% %PINGHOST4%) DO SET PINGHOST=%%A&& CALL :CHECKLOSS
FOR %%A in (%PINGHOST1% %PINGHOST2% %PINGHOST3% %PINGHOST4%) DO SET PINGHOST=%%A&& CALL :CHECKLAG
CALL :CHECKLAGAVRAGE
CALL :SENDMSG
IF "%DEBUG%" == "0" CALL :CLEANUP


GOTO :EOF
:CHECKGATEWAY
:: Check if GATEWAY is up
ping -n 1 %GATEWAY%>NUL 2>&1
IF NOT "%ERRORLEVEL%" == "0" (
 SET MSG=1
 SET ALERTMSG=Alert triggered because gateway %GATEWAY% could not be reached
 ECHO !ALERTMSG!>%TEMP%\msgfile.txt
 MSG %MSGUSER% /TIME:1440<%TEMP%\msgfile.txt
 SET HALT=1
)

GOTO :EOF
:CHECKROUTE
ping -n 1 %CHECKROUTEIP%>"%TEMP%\ping-%CHECKROUTEIP%.tmp" 2>&1
FINDSTR /I "Destination.net.unreachable" "%TEMP%\ping-%CHECKROUTEIP%.tmp"
IF "%ERRORLEVEL%" == "0" (
 SET MSG=1
 SET ALERTMSG=Alert triggered because %CHECKROUTEIP% could not be reached ^(Destination net unreachable^)
 ECHO !ALERTMSG!>%TEMP%\msgfile.txt
 MSG %MSGUSER% /TIME:1440<%TEMP%\msgfile.txt
 SET HALT=1
)
IF "%HALT%" == "1" GOTO :EOF
tracert %CHECKROUTEIP%>"%TEMP%\tracert-%CHECKROUTEIP%.tmp" 2>&1
FINDSTR /I "Destination.net.unreachable" "%TEMP%\tracert-%CHECKROUTEIP%.tmp"
IF "%ERRORLEVEL%" == "0" (
 SET MSG=1
 SET ALERTMSG=Alert triggered because %CHECKROUTEIP% could not be reached ^(Destination net unreachable^)
 ECHO !ALERTMSG!>%TEMP%\msgfile.txt
 MSG %MSGUSER% /TIME:1440<%TEMP%\msgfile.txt
 SET HALT=1
)

GOTO :EOF
:CHECKDNS
:: DNS check
nslookup %PINGHOST%>"%TEMP%\nslookup-%PINGHOST%.tmp" 2>&1
FINDSTR /I "Non-existent.domain" "%TEMP%\nslookup-%PINGHOST%.tmp"
IF "%ERRORLEVEL%" == "0" (
 SET MSG=1
 SET ALERTMSG=Alert triggered because of DNS error - %PINGHOST% could not be resolved
 ECHO !ALERTMSG!>%TEMP%\msgfile.txt
 SET HALT=1
 MSG %MSGUSER% /TIME:1440<%TEMP%\msgfile.txt
)
IF "%HALT%" == "1" GOTO :EOF
FINDSTR /I "DNS.request.timed.out" "%TEMP%\nslookup-%PINGHOST%.tmp"
IF "%ERRORLEVEL%" == "0" (
 SET MSG=1
 SET ALERTMSG=Alert triggered because of DNS error - %PINGHOST% DNS request timed out
 ECHO !ALERTMSG!>%TEMP%\msgfile.txt
 SET HALT=1
 MSG %MSGUSER% /TIME:1440<%TEMP%\msgfile.txt
)

GOTO :EOF
:PING
PING -n %NUMPINGS% %PINGHOST%>"%TEMP%\ping-%PINGHOST%.tmp" 2>&1
FINDSTR /R /I "Request.timed.out" "%TEMP%\ping-%PINGHOST%.tmp" >NUL 2>&1
IF "%ERRORLEVEL%" == "0" (
 SET MSG=1
 SET ALERTMSG=Alert triggered because of PING error - %PINGHOST% - Request timed out
 ECHO !ALERTMSG!>%TEMP%\msgfile.txt
 SET HALT=1
 MSG %MSGUSER% /TIME:1440<%TEMP%\msgfile.txt
)


GOTO :EOF
:CHECKLOSS
:: Get system time regardless of system language settings
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' SET ldt=%%j
SET YEAR=%ldt:~0,4%
SET MONTH=%ldt:~4,2%
SET DAY=%ldt:~6,2%
SET HOUR=%ldt:~8,2%
SET MINUTE=%ldt:~10,2%
SET SECOND=%ldt:~12,2%

::Set the current time in a format that can go in a filename.
SET MYTIME=%HOUR%:%MINUTE%
SET FILETIME=%HOUR%-%MINUTE%
SET FILEDATE=%YEAR%-%MONTH%-%DAY%

FINDSTR /R "Lost.=.0" "%TEMP%\ping-%PINGHOST%.tmp" >NUL 2>&1
IF NOT "%ERRORLEVEL%" == "0" ( 
 SET /A LOSS=%LOSS%+1
 IF "%DEBUG%" == "1" ECHO %PINGHOST% LOSS=%LOSS%
 COPY /Y "%TEMP%\ping-%PINGHOST%.tmp" "%LOGPATH%\ping-%FILEDATE%--%FILETIME%.log"
)

GOTO :EOF
:CHECKLAG
FOR /f "tokens=10 delims=^=,ms" %%A IN ('FINDSTR /R "Average.[>=].[0-9]*ms" "%TEMP%\ping-%PINGHOST%.tmp"') DO (
 IF "%DEBUG%" == "1" ECHO %PINGHOST% "%%A" ms
 SET /A PINGHOSTLAG=%PINGHOSTLAG%+"%%A"
 IF "%DEBUG%" == "1" ECHO %PINGHOSTLAG%
)

GOTO :EOF
:CHECKLAGAVRAGE
SET /A LAGAVRAGE=%PINGHOSTLAG%/4
IF "%DEBUG%" == "1" ECHO %LAGAVRAGE%

IF %LAGAVRAGE% LEQ %LATENCY% (
 SET LAG=0
) ELSE (
 SET LAG=1
)

GOTO :EOF
:SENDMSG
SET MSG=0
IF "%LAG%" == "1" (
 SET MSG=1
 SET ALERTMSG=Alert triggered because of high response time
)

IF "%LOSS%" == "1" (
 SET MSG=1
 SET ALERTMSG=Alert triggered because of packet loss
)

IF "%MSG%" == "0" GOTO :EOF


:: Set LAGMSG
FOR %%A in (%PINGHOST1% %PINGHOST2% %PINGHOST3% %PINGHOST4%) DO (
 SET PINGHOST=%%A
 FOR /f "tokens=1-3 delims=," %%a IN ('FINDSTR "Average" "%TEMP%\PING-!PINGHOST!.tmp"') DO (
 ECHO %%a, %%b, %%c>"%TEMP%\LAGMSG-!PINGHOST!.tmp"
 )
)

:: Set LOSSMSG
FOR %%A in (%PINGHOST1% %PINGHOST2% %PINGHOST3% %PINGHOST4%) DO (
 SET PINGHOST=%%A
 FOR /f "tokens=1-3 delims=," %%a IN ('FINDSTR "Packets" "%TEMP%\PING-!PINGHOST!.tmp"') DO (
 ECHO %%a, %%b, %%c>"%TEMP%\LOSSMSG-!PINGHOST!.tmp"
 )
)

:: Send the message
ECHO %ALERTMSG%>%TEMP%\msgfile.txt
ECHO. >>%TEMP%\msgfile.txt
ECHO Approximate round trip times in milli-seconds: %LAGAVRAGE%ms>>%TEMP%\msgfile.txt
ECHO. >>%TEMP%\msgfile.txt
FOR %%A in (%PINGHOST1% %PINGHOST2% %PINGHOST3% %PINGHOST4%) DO (
 SET PINGHOST=%%A
 ECHO !PINGHOST!>>%TEMP%\msgfile.txt
 TYPE "%TEMP%\LAGMSG-!PINGHOST!.tmp">>%TEMP%\msgfile.txt
)
ECHO. >>%TEMP%\msgfile.txt
FOR %%A in (%PINGHOST1% %PINGHOST2% %PINGHOST3% %PINGHOST4%) DO (
 SET PINGHOST=%%A
 ECHO Ping statistics for !PINGHOST!>>%TEMP%\msgfile.txt
 TYPE "%TEMP%\LOSSMSG-!PINGHOST!.tmp">>%TEMP%\msgfile.txt
)

MSG %MSGUSER% /TIME:1440<%TEMP%\msgfile.txt

:CLEANUP
IF EXIST "%TEMP%\PING-*.tmp" DEL /F "%TEMP%\PING-*.tmp" >NUL 2>&1
IF EXIST "%TEMP%\LOSSMSG-*.tmp" DEL /F "%TEMP%\LOSSMSG-*.tmp" >NUL 2>&1
IF EXIST "%TEMP%\LAGMSG-*.tmp" DEL /F "%TEMP%\LAGMSG-*.tmp" >NUL 2>&1
IF EXIST "%TEMP%\nslookup-*.tmp" DEL /F "%TEMP%\nslookup-*.tmp" >NUL 2>&1
IF EXIST "%TEMP%\tracert-*.tmp" DEL /F "%TEMP%\tracert-*.tmp" >NUL 2>&1
IF EXIST "%TEMP%\msgfile.txt" DEL /F "%TEMP%\msgfile.txt">NUL 2>&1
IF EXIST "%LOGPATH%\writetest.tmp" DEL /F "%LOGPATH%\writetest.tmp">NUL 2>&1
IF EXIST "%LOGPATH%\_lock.tmp" DEL /F "%LOGPATH%\_lock.tmp">NUL 2>&1