难道一个bat文件知道它的名字,它可以删除自身 [英] Does a bat file know its name and can it delete itself

查看:180
本文介绍了难道一个bat文件知道它的名字,它可以删除自身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的剧本某些时候,我想蝙蝠脚本删除自身。这要求脚本知道它的名字,然后使用该名称来删除它本身。这可能吗?

At some point in my script, I'd like the bat script to delete itself. This requires that the script know its name and then to use that name to delete itself. Is this possible?

推荐答案

现有的答案都不提供了一个批处理文件删除自身和退出没有任何明显的错误消息清洁的方式。

None of the existing answers provide a clean way for a batch file to delete itself and exit without any visible error message.

只需包括删除%〜F0不删除脚本,但它也导致一个丑陋的批处理文件无法找到。的错误消息。

Simply including del "%~f0" does delete the script, but it also results in an ugly "The batch file cannot be found." error message.

如果它是确定的脚本关闭父CMD过程(控制台窗口),再细了以下工作没有任何错误信息:

If it is OK for the script to close the parent CMD process (the console window), then the following works fine without any error message:

del "%~f0"&exit

但是,如果你希望脚本删除自己退出的没有它是一个比较复杂一点的关闭父CMD过程,并没有任何错误消息。

But it is a bit more complicated if you want the script to delete itself and exit without closing the parent CMD process, and without any error message.

方法1:启动了实际执行删除同一控制台窗口中运行的第二个过程。在 EXIT / B 可能不是必要的,但我把它放在最大化之前启动的进程试图删除文件批处理脚本将关闭的可能性。

Method 1: Start a second process that runs within the same console window that actually performs the delete. The EXIT /B is probably not necessary, but I put it in to maximize the probability that the batch script will close before the STARTed process attempts to delete the file.

start /b "" cmd /c del "%~f0"&exit /b

方法2:创建和控制权转移给删除本身以及来电另一个临时批处理文件,但不使用CALL,并重定向错误输出到NUL

Method 2: Create and transfer control to another temp batch file that deletes itself as well as the caller, but don't use CALL, and redirect stderr to nul.

>"%~f0.bat" echo del "%~f0" "%~f0.bat"
2>nul "%~f0.bat"

这篇关于难道一个bat文件知道它的名字,它可以删除自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆