顺序执行任务

时间:2012-10-09 20:35:33

标签: vbscript batch-file cmd

我需要优雅地终止(通过.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完成时我想要执行最后两个命令 (即应用程序在最终结束后关闭)提示已由用户解决。

有办法吗?

1 个答案:

答案 0 :(得分: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