1

我需要优雅地终止(通过 .bat 或 .vbs)特定应用程序,以便安全地覆盖其目录中的(只读)文件,然后删除其子目录之一中的所有文件。

我有这样的想法:

@echo off
taskkill /t /im App.exe
ping -n 5 127.0.0.1 > nul
xcopy /y /r "C:\Some path\My File.ext" "C:\App path"
Del /f /q "C:\App path\App sub-directory\*.*"

而不是等待固定的时间(在上面的示例中为 5 秒),我希望在 taskkill 完成时才执行最后两个命令(即在用户解决最终提示后关闭应用程序)。

有没有办法做到这一点?

4

1 回答 1

3

批量你可以这样做:

@echo off

setlocal EnableDelayedExpansion

for /f "tokens=2" %%p in ('tasklist /fi "imagename eq App.exe" /fo list ^| find "PID:"') do set pid=%%p

taskkill /t /pid %pid%

:wait
ping -n 2 127.0.0.1 >nul
tasklist /fi "pid eq %pid%" /fo list | find "PID:"
if %errorlevel% equ 0 goto wait

xcopy /y /r "C:\Some path\My File.ext" "C:\App path"
del /f /q "C:\App path\App sub-directory\*.*"

endlocal

不过,我更喜欢 VBScript。

Set wmi = GetObject("winmgmts://./root/cimv2")
Set sh  = CreateObject("WScript.Shell")
query = "SELECT * FROM Win32_Process WHERE Name = 'App.exe'"

For Each p In wmi.ExecQuery(query)
  ' p.Terminate would forcibly terminate the process (like "taskkill /t /f")
  sh.Run "taskkill /t /pid " & p.ProcessId, 0, False
Next

Do While wmi.ExecQuery(query).Count > 0
  WScript.Sleep 100
Loop

Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists("C:\App path\My File.ext") Then
  fso.DeleteFile "C:\App path\My File.ext", True
End If
fso.CopyFile "C:\Some path\My File.ext", "C:\App path\", True
fso.DeleteFile "C:\App path\App sub-directory\*.*", True

除了删除目标文件,您还可以删除只读标志:

Set f = fso.GetFile("C:\App path\My File.ext")
f.Attributes = f.Attributes And Not 1
于 2012-10-09T21:40:27.680 回答