我需要创建一个vbs脚本(出于维护目的),将foo.txt重命名为foo.bat并启动foo.bat,当foo.bat结束时,再次将foo.bat重命名为foo.txt
这是我的脚本vbs
On Error Resume next
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "foo.txt", "foo.bat"
SCRIPT = "foo.bat"
Set objShell = CreateObject("Wscript.Shell")
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
NewPath = objFSO.BuildPath(strFolder, SCRIPT)
set objshell = createobject("wscript.shell")
objshell.Run NewPath, vbHide, true
Fso.MoveFile "foo.bat", "foo.txt"
On Error GoTo 0
脚本执行良好。将foo.txt重命名为foo.bat。启动foo.bat,但不希望foo.bat结束并将其重命名为foo.txt。
我更改了这一行,什么也没发生:
objshell.Run NewPath, vbHide, 1, true
我需要什么或我做错了什么?
替代解决方案(无VBScript):(由@KenWhite建议)
代码:
On Error Resume next
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "foo.txt", "foo.bat"
SCRIPT = "foo.bat"
Set objShell = CreateObject("Wscript.Shell")
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
NewPath = objFSO.BuildPath(strFolder, SCRIPT)
set objshell = createobject("wscript.shell")
objshell.Run NewPath, true
On Error GoTo 0
在foo.bat的末尾:
ren foo.bat foo.txt
exit
谢谢
答案 0 :(得分:1)
这是一个可能的解决方案,以防万一有人想知道如何解决这个问题而不求助于上述替代方案。
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "foo.txt", "foo.bat"
SCRIPT = "foo.bat"
Set objShell = CreateObject("Wscript.Shell")
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
NewPath = objFSO.BuildPath(strFolder, SCRIPT)
set objshell = createobject("wscript.shell")
objshell.Run "%COMSPEC% /c " & NewPath, 1, true
' Changes start here
'===================================================================
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
' Hold execution until cmd.exe process is done
do
' Get cmd.exe processes
Set colProcessList = objWMIService.ExecQuery _
("Select Name from Win32_Process WHERE Name LIKE 'cmd.exe'")
WScript.Sleep 250
Loop while colProcessList.count > 0
Fso.MoveFile "foo.bat", "foo.txt"