vendredi 4 septembre 2020

Read digit from file, use digit in command, write new digit to file [duplicate]

I am trying to write a batch file that can automatically switch the main monitor of my multimonitor set-up. NirCMD is a tool that can do this by running the command

nircmd.exe setprimarydisplay 2

I want to create a bat file that can automatically switch between two monitors. My current idea is to save the current primary display in a text file, active.txt. So it would just contain the digit of the active monitor, e.g. 2, where 1 is the default.

When the script is launched, the active.txt is read (if present, otherwise default to display 1). The digit in that file should then be used in an if/else statement to determine which new value to use.

I am familiar with other languages where shorthand if/else statements could make this easier. I am not familiar with batch files, though, so any help is appreciated. I came up with the following which does not seem to work - it does work for the outer if/else, and it creates a new file. But it seems to fail in the inner if/else. I assume because I do something wrong with the variable checking.

@echo off
IF EXIST active.txt (
    set /p display=< active.txt
    del active.txt
    IF "%display%"=="1" (
        nircmd.exe setprimarydisplay 2
        echo 2 > active.txt
    ) ELSE (
        nircmd.exe setprimarydisplay 1
        echo 1 > active.txt
    )
) ELSE (
    nircmd.exe setprimarydisplay 1
    echo 1 > active.txt
)

Update after comments: unfortunately, still not working as expected. The first run works and correctly sets the active display to the first monitor and writes the file. However, subsequent runs do not change anything.

@echo off
SETLOCAL EnableDelayedExpansion
IF EXIST active.txt (
    set /p display=< active.txt
    del active.txt
    IF "%display%"=="1" (
        nircmd.exe setprimarydisplay 2
        > "active.txt" echo 2
    ) ELSE (
        nircmd.exe setprimarydisplay 1
       > "active.txt" echo 1
    )
) ELSE (
    nircmd.exe setprimarydisplay 1
    > "active.txt" echo 1
)

Aucun commentaire:

Enregistrer un commentaire