spoko
spoko

Reputation: 121

VBScript not working properly when scheduled

I have a VBScript to back up several registry keys into a single file:

Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

arrRegPaths = Array( _
      "HKEY_CURRENT_USER\RegKey1\", _
      "HKEY_CURRENT_USER\RegKey2\", _
      "HKEY_CURRENT_USER\RegKey3\" _
      )

Const intForReading = 1
Const intUnicode = -1

strFileName = objShell.ExpandEnvironmentStrings("%UserProfile%") & "\FolderName\FileName.reg"

Set objRegFile = objFSO.CreateTextFile(strFileName, True, True)
objRegFile.WriteLine "Windows Registry Editor Version 5.00"

For Each strRegPath In arrRegPaths
      strCommand = "cmd /c REG EXPORT " & strRegPath & " " & Replace(strRegPath, "\", "_") & ".reg"
      objShell.Run strCommand, 0, True
      If objFSO.FileExists(Replace(strRegPath, "\", "_") & ".reg") = True Then
            Set objInputFile = objFSO.OpenTextFile(Replace(strRegPath, "\", "_") & ".reg", intForReading, False, intUnicode)
            If Not objInputFile.AtEndOfStream Then
                  objInputFile.SkipLine
                  objRegFile.Write objInputFile.ReadAll
            End If
            objInputFile.Close
            Set objInputFile = Nothing
            objFSO.DeleteFile Replace(strRegPath, "\", "_") & ".reg", True
      End If
Next

objRegFile.Close
Set objRegFile = Nothing

I can run it directly from Explorer (Win10), directly from CMD, or with WScript/CScript, and it works perfectly. Takes about 2 seconds to complete, and the output file has everything it's supposed to have.

But when I try to run it as a scheduled task, it never finishes running. I've let it sit for several minutes, before manually killing it. When I look at the output file after this, all it has is the first line, Windows Registry Editor Version 5.00. So I know the script is finding the target file OK, and it's running the first WriteLine. But after that, it hangs or something.

How can I make it work as a scheduled task?

Upvotes: 0

Views: 509

Answers (2)

spoko
spoko

Reputation: 121

Got it figured out, and it actually had little to do with the code. I'll post the answer in case anyone else runs across something similar. It turns out that the problem was in the scheduled task itself—I needed to put a folder in the "Start in" box (when specifying the action to be scheduled). I assume this is because the script outputs to temp files along the way, so it needed a place to put those. Anyway, once I filled in that blank, it began running successfully.

Upvotes: 1

Rno
Rno

Reputation: 887

Haven't tried your code, but you send a commandline command from within your script. That seems counterintuitive to me. You are probably better off by tapping into the registry directly from your script. You can find examples of how to do that here: https://learn.microsoft.com/en-us/windows/desktop/WmiSdk/wmi-tasks--registry

Upvotes: 1

Related Questions