防止已删除的文件在启动文件夹中运行

防止已删除的文件在启动文件夹中运行

我的启动文件夹中有一个名为 everytime.bat 的批处理脚本,它会删除除批处理脚本之外的所有文件。

@echo off
REM delete everything in startup except this file
cd "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
for %%i in (*.*) do if not "%%i"=="everytime.bat" del /s /q /f "%%i"

这部分工作正常。问题是我向启动文件夹添加了一个文本文件来测试此工作流程,而 Windows 一直尝试打开不再存在的文本文件。有什么办法可以解决这个问题吗?

答案1

您也可以在参数中使用变量替换for,其中参数%0是您的file.bat

    %~0   - expands %0 removing any surrounding quotes (")
    %~f0  - expands %0 to a fully qualified path name only
    %~n0  - expands %0 to a file name only
    %~x0  - expands %0 to a file extension only

    %%~nx0 => expands %%~ to a file name and extension

尝试使用一个更具体的命令来防止删除你的bat文件%~nx0

@echo off

REM delete everything in startup except this file
set "_Startup=C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
for /f tokens^=* %%i in ('where /r "%_Startup%" *.*^|findstr /vi "%~x0  Desktop.ini"')do echo\ del /q /f "%%~i"
where /r "%_Startup%" *.*
List all files recursively in your folder: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

^|findstr /v /i "%~x0"
/v == List all files NOT containing the file bat Name.eXtension (the same as %~nx0) and the hidden system file Desktop.ini  
/i == Ignores the case UPPER/lower of characters when searching for the string.  

观察:此文件夹中有一个隐藏的desktop.ini文件,如果您已经删除此desktop.ini文件并想要恢复它:

  1. 打开记事本,将下面的内容粘贴/保存到desktop.ini
    同一个文件夹中并命名:
[.ShellClassInfo]
LocalizedResourceName=@%SystemRoot%\system32\shell32.dll,-21787
  1. 要返回隐藏属性,请运行:
 attrib +r "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\desktop.ini"

  • 为了让你的 bat 文件desktop.ini也能防止文件被删除,你可以替换find /v /ifindstr /vi并添加desktop.ini为多重过滤器:
@echo off

REM delete everything in startup except this file and desktop.ini
set "_Startup=C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
for /f tokens^=* %%i in ('where /r "%_Startup%" *.*^|findstr /vi "%~nx0 
 Desktop.ini"')do echo\ del /q /f "%%~i"
where /r "%_Startup%" *.*
List all files recursively in your folder: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

^|findstr /vi "%~x0" is the same concatenate: /v /i
/v == List all files NOT containing the file bat Name.eXtension, the same as %~nx0 also Desktop.ini
/i == Ignores the case UPPER/lower of characters when searching for the string.  
  • 笔记:测试并检查输出,如果看起来正确,只需删除echo\
echo\ del /q /f "%%~i"

相关内容