acgbox
acgbox

Reputation: 324

rename a file using VBScript, launch file, wait, and rename again

I need to create a vbs script (for maintenance purposes) that renames foo.txt to a foo.bat and launch foo.bat and when foo.bat ends, rename foo.bat again to foo.txt

This is my script 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

the script executes well. Rename foo.txt to foo.bat. Launches foo.bat, but does not expect foo.bat to end and renames it to foo.txt.

I changed this line, nothing happens:

objshell.Run NewPath, vbHide, 1, true

What do I need or what did I do wrong?

Alternative Solution (no VBScript): (By suggestion of @KenWhite)

code:

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

And at the end of foo.bat:

ren foo.bat foo.txt
exit

Thanks

Upvotes: 0

Views: 343

Answers (1)

user10750522
user10750522

Reputation:

Here is a possible solution just in case anyone is wondering how to solve this problem without resorting to the alternate proposal mentioned above.

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"

Upvotes: 1

Related Questions