CMD script practical tutorial

To write a custom shutdown CMD script file on Windows 11, you can create a text file with the extension .bator .cmdand write the script in it.

1. Commonly used grammar

1. Note: rem

rem 这里是注释

2. Pause: pause

pause: Pause the batch file being executed and prompt the user to press a key to continue execution.

rem cmd脚本文件代码
pause

image-20230922151349814

3. Print text: echo

echo: print text

  • echo %os%: Display operating system name;
  • echo off: Prevent specific commands in the batch file from being output, and only output the execution results.
  • @echo off: echo offHide the command itself based on

image-20230922152124282

4. Define variables: set

set: Set user-defined or named environment variables. It is temporarily stored in memory and destroyed after the command is executed.

set THE_KING=Elvis
echo %THE_KING%  
pause

Insert image description here

5. Jump: goto

label: Use colon to set the label, which can be used as gotothe jump position of

echo Start
goto end
echo I can guarantee this line will not be executed
:end
echo End
pause

pause

image-20230922152526004

You can see echo I can guarantee this line will not be executedit is skipped directly.

6, condition: if

  • if:Conditional statements

    • exist: Test whether the file exists
    • %Receive parameters: %Pass parameters through to %1represent the first parameter and %2represent the second parameter;
    if %1 == start goto start
    if %1 == stop goto stop
    goto invalid
    
    :start
    echo Starting appincation
    goto end
    
    :stop
    echo Stopping application
    goto end
    
    :invalid
    echo Invalid parameter
    
    :end
    pause
    

    image-20230922155958313

    Here %1is the first parameter received when executing the script file. You can see that in the above case, %1it is actually start.

7. Accept parameter displacement: shift

  • shift: Move the received parameter backward by one position, such as %2giving the value of %1, %3giving the value of %2, and then you can use it %0to get the first parameter.

    //还是上面的代码,改成如下代码,效果是一样的:
    shift
    if %0 == start goto start
    if %0 == stop goto stop
    ...后面代码不变
    

8. Call an external script file: call

Created in the same directory cmd2.cmd, the code is as follows:

echo 这里是cmd2.cmd中的内容

Create again cmdScript.cmd, the code is as follows:

chcp 65001
call cmd2.cmd

pause

Double-click to execute cmdScript.cmd, the effect is as follows:

image-20230922160829535

9. Set environment variables: setLocal

  • setLocal: Used in batch scripts. Modifications to environment variables are only effective in the current batch script. When endLocala command is encountered, the value of the environment variable at the end of the batch file will be restored to its original value. Above we use setlocal enabledelayedexpansionthe enable variable delay.

10. Create a new terminal window: start

  • start: Open a new Windows console and specify a name.

    start "My Title" echo hello 
    pause
    

    image-20230922161459378

Double-click to open the script file, and the script will automatically open a My Titlewindow named 2 and print hello.

11. The judgment is the same

  • ==: Determine whether the strings are the same

    @echo off
    chcp 65001
    
    set str1=Hello
    set str2=World
    
    if "%str1%" == "%str2%" (
        echo 字符串相同
    ) else (
        echo 字符串不同
    )
    
    REM 不要关闭窗口
    pause
    

    image-20230922165101792

  • equ、gtr、lss: Determine the size of a number

2. Practical cases

1. Receive input

Create cmda script file with the following code and double-click to run:

@echo off
setlocal enabledelayedexpansion

REM 提示用户输入内容
set /p userInput=please input: 

REM 打印用户输入的内容
echo you input is: !userInput!

endlocal
REM 不要关闭窗口
pause

The effect after running is as follows:

print

It should be noted that the prompt text on the interface you input is:cannot be in Chinese, otherwise an error will be reported: XXX: is not recognized as an internal or external command,operable program or batch file.. If you want to use Chinese, echothe following variables must be used %变量名%and cannot be used !变量名!.

2. Automatic shutdown

Create a file 定时关机.cmdand enter the following content:

@echo off
chcp 65001
setlocal enabledelayedexpansion

:start
set /p second=请输入倒计时时长(秒):
set S=!second!

if %S% lss 30 (
	echo 您设定的时间太短,请重新设置(请务必超过30s)
	goto start
) else (
	echo.
	echo 将在 【%S%秒】 后为您关机,请检查以下事项:
	echo - 文件+代码是否都已保存和提交?
	echo - 任务和周报是否都已填报?
	echo.
	goto sure
)

:sure
set /p sure=确定关机[y/n]:
echo !sure!
if "!sure!"=="y" (
	goto launch
)
goto end

:launch
timeout /t %S%
shutdown /s /f /t 0
goto end

:end
endlocal

REM 不要关闭窗口
pause

This script first turns off the echo of the command line window ( @echo off), then displays a message, waits for 30 seconds (the waiting time can be adjusted as needed), and finally executes the shutdown command.

  • chcp 65001:Set Chinese character encoding (to prevent Chinese garbled characters)

  • shutdown: shutdownCommand is used to perform shutdown operation.

  • /s: This parameter tells shutdownthe command to perform a shutdown operation.

  • /f: This parameter forces all applications to close without waiting for their response.

  • /t 0: This parameter means do not wait and perform the shutdown operation immediately.

  • pause: Wait for the user to press any key before closing

  • setlocal enabledelayedexpansion: Turn on variable delay

  • endlocal: Close variable delay, setlocal enabledelayedexpansionappears in pairs with

  • echo.: print blank line

The cmd window will pop up automatically after execution (the space bar can count down the terminal):

image-20230922185455773

3. Receive digital input and compare sizes

The script code is as follows:

@echo off
chcp 65001
setlocal enabledelayedexpansion

set /p n1=num1:
set /p n2=num2:

set num1=!n1!
set num2=!n2!

if %num1% equ %num2% (
    echo num1和num2相同
) else if %num1% gtr %num2% (
    echo num1大于num2
) else if %num1% lss %num2% (
    echo num1小于num2
)

endlocal
REM 不要关闭窗口
pause

image-20230922171049662

4. Start the front-end project script

@echo off
chcp 65001
setlocal enabledelayedexpansion

set projectName=项目名称
set projectPath=D:\Codes\project1

REM 提示用户输入内容
set /p env=即将启动【%projectName%】,请指定环境[test/prod]: 

REM 打印用户输入的内容
echo Running...:%projectName%[!env!]

set ENV=!env!

cd /d %projectPath%

if (%ENV%)==() (
	goto empty
) else if "%ENV%"=="test" (
	goto env
) else (
	goto env
)

:empty
echo 正在启动dev环境...
pnpm start
goto end

:env
echo 正在启动%ENV%环境...
pnpm start:%ENV%
goto end

:end
endlocal
REM 不要关闭窗口
pause
  • set /p env=即将启动【产品中心】,请指定环境[test/prod]:: Receive an input and define the receiving variable env
  • set ENV=!env!: Assign input to ENVvariable
  • cd /d D:\Codes\Product-Center: Switch to drive D and enter the specified project directory
  • if... else... if else... : Determine which environment to start
  • goto: Jump to the specified code position.
  • if (%ENV%)==(): Determine whether the input text is empty. This method is required. ==The actual test is invalid.

The execution effect is as follows:

image-20230922173055600

Guess you like

Origin blog.csdn.net/bobo789456123/article/details/133178858