dos脚本语法学习
阅读原文时间:2023年07月08日阅读:1
  • 一个dos批处理脚本,通过关键字搜索注册表并删除,坑很多,语法也很怪异,详情看注释

    @echo off
    ::声明采用UTF-8编码,避免中文乱码问题,>NUL可以吞掉chcp输出的内容
    chcp 65001 >NUL

    set key_word="hello"
    set recursive=1
    set end_key_word=End

    ::now let us do it.
    echo "--------------------------------------------------------------------------------------------"

    call :search_del_reg_func HKEY_CLASSES_ROOT
    call :search_del_reg_func HKEY_CURRENT_USER
    call :search_del_reg_func HKEY_LOCAL_MACHINE
    call :search_del_reg_func HKEY_USERS
    call :search_del_reg_func HKEY_CURRENT_CONFIG
    goto :end_print

    ::search and delete the regedit function
    :search_del_reg_func
    set search_path=%1
    set reg_cmd="REG QUERY %search_path% /f %key_word% /s "
    ::not recursive
    if %recursive%==0 (
    echo Scanning normally… key_word:%key_word% Root Path: %search_path%
    set reg_cmd="REG QUERY %search_path% /f %key_word% "
    )else (
    echo Scanning recursivly… key_word:%key_word% Root Path: %search_path%
    )

    FOR /F "tokens=* " %%a IN ('%reg_cmd%') do (
    ::使用block的方式来执行,因为for里面不能使用goto,会破坏for循环结构
    call :for_func %%a %%b
    echo:
    echo:
    )
    goto :eof

    :: for loop's block
    :for_func
    set item="%1"
    set flags=%item:~1,3%
    set flags=%flags:"=%
    if "%flags%"=="%end_key_word%" (
    goto end_flags
    )

    if "%flags%"=="" (
    goto end_flags
    )

    ::延迟userinput的解析,在dos里面,()里面的代码会被提前解析,如果不设置该选项的话,会导致%choice%里面的东西始终是空的
    setlocal EnableDelayedExpansion

    set item="%1"
    set /p choice=Really delete[%1]? y=yes n=no:
    ::没有真正的or,所以用这种很挫的方式来实现
    if "!choice!"=="y" goto delete_reg
    if "!choice!"=="yes" goto delete_reg
    if "!choice!"=="n" goto not_del_reg
    if "!choice!"=="no" goto not_del_reg
    goto not_del_reg

    :delete_reg
    reg delete %item% /f
    echo WARNNING: You just deleted reg[%item%]!!!!!
    goto end_flags

    :not_del_reg
    echo INFO: You omit this reg [%item%]!!!
    goto end_flags

    :end_flags
    endlocal

    goto :eof

    :end_print
    echo "-------------------------------------OVER---------------------------------------------------"

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章