Home > Net >  I need help fixing a batch script I've created
I need help fixing a batch script I've created

Time:06-29

:test
powershell -Command "exit (Get-CimInstance -Namespace root\wmi -ClassName WmiMonitorBasicDisplayParams | Select-String -Pattern 'InstanceName').length"
set nMons=%ERRORLEVEL%
if %errorlevel% equ 2 start C:\BookOfSixNew\ShellStartEdge.bat
timeout 10
goto:test

What this loop does, is check every 10 seconds for the number of monitors connected to my PC, and restart a certain app if it detects more than 2 monitors, afterwards the script shuts down.

I need help keeping this script running but I only want it to restart the app when the monitor count changes.

This script runs at startup, when there is 1 monitor connected to my PC.

From this point forward it keeps checking my monitor count until a second monitor is connected, and when it finds a second monitor, it restarts the app and it shuts down right away.

All good for now, but from this point forward, I want the script to remain active, to keep checking for monitors, just in case one of the monitors is disconnected and reconnected later on, when it should restart the app once more.

My issue is, if the script remains active after the second monitor is connected, it keeps searching for monitors every 10 seconds, and because there are already 2 monitors connected, it will restart the app every 10 seconds.

How can I avoid this?

I want the script to take a break from checking my monitor count after it found the second monitor, until there is an actual difference made to the monitor count, like one monitor getting disconnected.

CodePudding user response:

You need your script to know the number of expected monitors to realize any change. Use a variable to save the old value to compare it with a new value:

@echo off
setlocal
REM get first number (at startup)
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile -Command "Exit (Get-CimInstance -NameSpace Root\WMI -Query \"SELECT * FROM WmiMonitorBasicDisplayParams WHERE Active = 'TRUE'\").Active.Length"
set OldNumber=%errorlevel%

:loop
timeout 10 >nul
REM get CurrentNumber
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile -Command "Exit (Get-CimInstance -NameSpace Root\WMI -Query \"SELECT * FROM WmiMonitorBasicDisplayParams WHERE Active = 'TRUE'\").Active.Length"
set CurrentNumber=%errorlevel%
echo DEBUG: CurrentNumber/old = %CurrentNumber%/%OldNumber%
if %CurrentNumber% gtr %OldNumber% (
   set OldNumber=%CurrentNumber%
   echo Found a new monitor
)
if %CurrentNumber% lss %OldNumber% (
   set OldNumber=%CurrentNumber%
   echo A monitor is now missing
)
goto :loop

Just add the commands that should execute when a monitor connects or disconnects.

  • Related