Regwrite nonpersistent value in the registry after restart [duplicate] - windows

This question already has answers here:
File checking on Windows Startup is failing [duplicate]
(2 answers)
Closed 2 years ago.
I have this script (below), not the best script but it works fine, however every time I restart my computer that new registry triplet is gone and I have no guess why.
I got no errors from this script, but if I let it run for a reasonably period of time a vbs Msgboxpops up with,
This script contains malicious content and has been blocked by your antivirus software.
I honestly don't think it is related but apparently I cannot post a question being concise due to text requirements limitations. Or is it related and the antivirus is wiping out that triplet? After this message the new register is still there (in the registry) but not after a restart.
Dim sKey
sKey = "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\so_Robocopy"
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim wshShell
Set wshShell = CreateObject("WScript.Shell")
If fso.FileExists("so_Robocopy.bat") Then
RegisterOnWindowsStartUp()
MsgBox "Backup message text"
Do While True
wshShell.Run Chr(34) & "so_Robocopy.bat" & Chr(34), 0
WScript.Sleep 300000
Loop
Else
RemoveFromRegistry()
End If
Function RemoveFromRegistry()
On Error Resume Next
wshShell.RegDelete sKey 'Error handling routine
End Function
Function RegisterOnWindowsStartUp()
If DoesRegistryExist = False Then
wshShell.RegWrite sKey, Chr(34) & WScript.ScriptFullName & Chr(34), "REG_SZ"
End If
End Function
Function DoesRegistryExist()
with CreateObject("WScript.Shell")
on error resume next
sValue = .regread(sKey)
DoesRegistryExist = (err.number = 0)
on error goto 0
End with
End Function

When you run the script, it will work fine, and no problem because you are running the script on the current directory and the so_Robocopy.bat existed on the same directory.
However, on Windows Startup, the script will execute on the Directory of Windows Startup and not on the original directory where your script is located.
Here's what happened to your code,
' Script execute from the Directory of Windows Starup
If fso.FileExists("so_Robocopy.bat") Then ' (1) There will be no so_Robocopy.bat on the Directory of Windows Startup, then this will return false.
RegisterOnWindowsStartUp()
MsgBox "Backup message text"
Do While True
wshShell.Run Chr(34) & "so_Robocopy.bat" & Chr(34), 0
WScript.Sleep 300000
Loop
Else (2) The condition is false, then remove the key from registry.
RemoveFromRegistry()
End If
Make sure you are looking from the original directory where your script is. You can use Scripting.FileSystemObject and WScript.ScriptFullName for that.
(1)
so_robocopy_file = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) & "\so_Robocopy.bat"
If fso.FileExists(so_robocopy_file) Then ' (2)
RegisterOnWindowsStartUp()
MsgBox "Backup message text"
Do While True
wshShell.Run Chr(34) & so_robocopy_file & Chr(34), 0 ' (3)
WScript.Sleep 300000
Loop
Else

Related

Open multiple .vbs one by one

i want .vbs script, to open multiple large files .vbs [i want to Open .vbs one by one] that do not make me, lag in PC.
0001.vbs, 0002.vbs, 0003.vbs, 0004.vbs
is can be different names like:
Anna.vbs, Diana.vbs, Antony.vbs, Andy.vbs
Example:
run C:\0001.vbs
MsgBox "0001.vbs IS END"
Next Open run C:\0002.vbs
MsgBox YES NO
MsgBox "0002.vbs IS END"
Next Open run C:\0003.vbs
MsgBox YES NO
MsgBox "0003.vbs IS END"
Next Open run C:\0004.vbs
MsgBox YES NO
MsgBox "0004.vbs IS END"
Thank you for you help.
Set Shell = CreateObject("WScript.Shell")
For i = 1 To 4
strFile = Right("0000" & i, 4) & ".vbs"
If MsgBox("Would you like to run " & strFile & "?", vbYesNo Or vbQuestion) = vbYes Then
Shell.Run "c:\" & strFile, 1, True
MsgBox strFile & " IS END"
End If
Next
Just make sure you pass True as the last parameter to Shell.Run so that this script waits until the others are done before reporting that they've ended.
Edit: To answer your comment about using names, you can loop through an array created on-the-fly.
For Each strName In Array("Anna", "Diana", "Antony", "Andy")
Next
To not make you wait for each sub process/.vbs before you start the next, don't use the 3rd/wait/true parameter to the .Run method:
a.vbs
Option Explicit
Dim oWSH : Set oWSH = CreateObject("WScript.Shell")
Dim v
For v = 0 To 1
oWSH.Run "cscript.exe " & v & ".vbs", 0, False
Next
MsgBox WScript.ScriptName & " done. " & Now()
0.vbs, 1.vbs
Option Explicit
Randomize
WScript.Sleep Rnd() * 1000
MsgBox WScript.ScriptName & " done. " & Now()
Evidence:
As you can see, a.vbs is finished first and 0.vbs and 1.vbs terminate in random/not in call order.
We have
0001.vbs, 0002.vbs, 0003.vbs, 0004.vbs
Assuming that you have this script file with the after mentioned files in the same directory.
If not, just modify the full path of your vbs files you want to run.
Instead of
WshShell.Run ".\0001.vbs"
You use for example:
WshShell.Run "c:\indel\0001.vbs"
This is the script:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run ".\0001.vbs"
WshShell.Run ".\0002.vbs"
WshShell.Run ".\0003.vbs"
WshShell.Run ".\0004.vbs"
What you need to do is make this code
do
msgbox("haha you cant close this")
CreateObject ("WScript.Shell").Run(".\Duplicate.vbs")
loop

Zipping a large folder fails

I am trying to archive logs to capture an intermittent fault where my logs are regularly overwritten. I wish to archive the logs to ensure I capture the required event.
I have written what appears to be funcional code to perform this, however if the folder is very large, the zip fails. If I point it to a smaller directory, it works without issue.
There is no error generated, and I would appreciate any assistance in identifying the cause.
As I have never programmed in VBS before, I apologise in advance if this seems a simple question.
Option Explicit
dim objFSO, objFolder, FolderToZip, ziptoFile
dim ShellApp, eFile, oNewZip, strZipHeader
dim ZipName, Folder, i, Zip
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("D:\Program Files\afolder")
Wscript.Sleep 2000
Set oNewZip = objFSO.OpenTextFile("C:\Archive\logs_" & day(date) & month(Date) & Year(date)& ".zip", 8, True)
strZipHeader = "PK" & Chr(5) & Chr(6)
For i = 0 to 17
strZipHeader = strZipHeader & Chr(0)
Next
oNewZip.Write strZipHeader
oNewZip.Close
Set oNewZip = Nothing
WScript.Sleep 5000
FolderToZip = "D:\Program Files\afolder"
ZipToFile = "C:\Archive\logs_" & day(date) & month(Date) & Year(date)& ".zip"
Set ShellApp = CreateObject("Shell.Application")
Set Zip= ShellApp.NameSpace(ZipToFile)
Set Folder= ShellApp.NameSpace(FolderToZip)
Zip.CopyHere(FolderToZip)
WScript.Sleep 2000
Your code is a little more complicated than it needs to be, but it works in principle. What's causing the failures you're experiencing with large folders is the fixed 2 second delay at the end:
WScript.Sleep 2000
CopyHere runs asynchronously, meaning that it runs in the background while the script continues. However, after 2 seconds delay the script terminates (and the Shell.Application instance with it), whether CopyHere has finished or not. When you have numerous/large files the processing may well take more than 2 seconds.
That's why your script works fine for small folders, but not for large ones. The copying simply isn't finished when the script terminates after 2 seconds.
To avoid this, replace the fixed delay with a check that compares the number of processed files to the total file count:
Set fso = CreateObject("Scripting.FileSystemObject")
Set app = CreateObject("Shell.Application")
zipfile = "C:\Temp\logs_" & Day(Date) & Month(Date) & Year(Date) & ".zip"
fldr = "C:\Temp\sample"
cnt = fso.GetFolder(fldr).Files.Count
'create a new empty zip file
fso.OpenTextFile(zipfile, 2, True).Write "PK" & Chr(5) & Chr(6) _
& String(18, Chr(0))
'start copying the files from the source folder to the zip file
Set zip = app.NameSpace(zipfile)
zip.CopyHere app.NameSpace(fldr).Items '<- runs asynchronously!
'wait for CopyHere to finish
Do
WScript.Sleep 100
Loop Until zip.Items.Count = cnt

Scripting MMC with vbscript

I would like to add a snap in via vbscript and I have been having a problem getting the snap in to add to the console. It will be run in a Windows 7 environment. If someone could have a look see and direct me in the right direction I would be most grateful. Thanks.
<code>
'Elevated privileges start
'Start of UAC workaround code
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If WScript.Arguments.length =0 Then
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute "wscript.exe", Chr(34) & _
WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
Else
consoleName = "C:\Burnett.msc"
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(consoleName) Then
Wscript.Echo "console already exists"
Else
On Error Resume Next
Set objMMC = CreateObject("MMC20.Application")
If err.Number <> 0 Then
Wscript.Echo "an error occurred. unable to create mmc console"
Wscript.Quit(0)
End If
objMMC.Show
Set objDoc = objMMC.Document
objDoc.snapins.add("Local Computer\Non-Administrators")
if err then
'Trap the error just after the statement where an error/exception can occur and handle it elegantly
msgbox("Snap-in Not found")
err.clear
end if
objDoc.ActiveView.StatusBarText = "Pane 1|Pane 2|Pane 3"
objMMC.UserControl = 1
objDoc.Name = consoleName
objDoc.Save()
End If
Set fso = Nothing
End If
</code>
"Local Computer\Non-Administrators" is just a system-supplied description for the particular configuration of a snap-in. In this case, the actual snap-in name is "Group Policy Object Editor". Thus to eliminate the error in the code change
objDoc.snapins.add("Local Computer\Non-Administrators")
to
objDoc.snapins.add("Group Policy Object Editor")
Unfortunately, this will only get you as far as MMC putting up a "Select Group Policy Object" dialog. You will then have to manually select the configuration you need using that dialog. As far as I can tell there is no way to supply Snapins.Add with the parameters to select the local non-admin users.
The code below will fully automate the process of setting up the snap-in. However, its reliance on SendKeys makes it extremely brittle. It worked on my system, but there's a good chance you'll need to modify the sequence of key strokes and/or the timing delays to make it work on your system. And once you get it working, there's no guarantee it will continue to do so as local conditions are mutable and can greatly effect the timing.
option explicit
if WScript.Arguments.Named.Exists("elevated") = false then
'Launch the script again with UAC permissions
CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ /elevated", "", "runas", 1
WScript.Quit
end if
Dim mmc : set mmc = WScript.CreateObject("MMC20.Application")
mmc.Show
mmc.UserControl = 1 'to keep MMC open
Dim oShell : set oShell = WScript.CreateObject("Wscript.Shell")
oShell.AppActivate "Console1"
WScript.Sleep 200
oShell.SendKeys "%f"
WScript.Sleep 200
oShell.SendKeys "m"
WScript.Sleep 400
oShell.SendKeys "group{TAB}{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{TAB}{TAB}{RIGHT}{TAB}Non{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{TAB}{ENTER}"
WScript.Sleep 1000
oShell.SendKeys "{TAB}{TAB}{TAB}{TAB}{ENTER}"

VBScript that Opens an ini file and a Config file in notepad

I work in a hospital environment and right now im doing PC deployments. Part of the deployment requires us to view 2 files on a network drive looking for information regarding the old systems. They use specific ports and or TTY's to view information in each department.
I am trying to create a VBS file that can open 2 files in 2 different notepad windows. The first one opens up but the pcview.cfg keeps giving me an error. Im trying to link to the same location that the HBOWEM32 is pointed to. Can anyone solve? For security reasons I have taken out the exact location of the network drive. The code below prompts for a specific folder name which is the old pc name. After entering that data it opens the HBOWEM32 files fine but says it cannot find the other part. I Have manually looked inside the folder and the pcview.cfg file DOES exist. I just want a faster way of opening these rather than brute forcing through the run prompt.
Here is the code.
CONST strDir = "<Netowrk Location)"
Dim WshShell
set objShell = CreateObject("WScript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")
function findFolder(strDir, strFlag)
set objFolder = objFSO.GetFolder(strDir)
for each objSubFolder in objFolder.SubFolders
if (inStr(objSubFolder.Name, strFlag)) then
findFolder = objSubFolder.Path
exit function
else
findFolder = findFolder (objSubFolder.Path, strFlag)
end if
next
end function
strFlag = inputBox("Enter Computer Name:")
strWeb = findFolder(strDir, strFlag) & "\HBOWEM32.ini"
objShell.Run strWeb
Set WshShell = CreateObject ("WScript.Shell")
WshShell.Run ("notepad.exe """ + "\\<same location as above>\Pcview.cfg""")
Use Option Explicit
Don't create variables you don't use (WshShell, objShell)
Improve your variable names (strFlag seems to be a computer name, strWeb seems to be the full specification of a file)
Don't lump different info into one variable (strWeb contains the folder path to re-use and the specific file name)
Use diagnostics output (at least while developing)
In code:
Option Explicit
...
Dim strComputer : strComputer = InputBox("Enter Computer Name:")
Dim strFolder : strFolder = findFolder(strDir, strComputer)
Dim strIniFSpec : strIniFSpec = objFSO.BuildPath(strFolder, "HBOWEM32.ini")
WScript.Echo "will run '" & strIniFSpec & "'"
objShell.Run strIniFSpec
Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
Dim strCfgFSpec : strCfgFSpec = objFSO.BuildPath(strFolder, "Pcview.cfg")
Dim strCmd : strCmd = "notepad.exe """ & strCfgFSpec & """"
WScript.Echo "will run '" & strCmd & "'"
WshShell.Run strCmd
(not tested, please be carefull)

How to output Command prompt to a log file using VBScript

I'm not a programmer so I don't want to overly irritate the fine folk in this forum. My issue is that I would like to use VBScript to Telnet into a Linux device, issue a DF command and output all response to a log file which I can parse later. I originally found a method to successfully Telnet but I have have been experimenting without success regarding the text file output requirement. The following code certainly does not work but I am wondering if I am even close to the correct method?
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("cmd /c dir")
WshShell.run"cmd" '*** open command window ***
WScript.Sleep 250
WshShell.SendKeys("{Enter}")
WshShell.SendKeys"telnet 10.13.2.2"
WshShell.SendKeys("{Enter}")
WScript.Sleep 2000
WshShell.SendKeys"root"
WshShell.SendKeys("{Enter}")
WScript.Sleep 1500
WshShell.SendKeys"password"
WshShell.SendKeys("{Enter}")
WScript.Sleep 1500
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.OpenTextFile("C:\VBSmemSize.txt", 2, True)
WshShell.SendKeys"df /mnt/cf"
WshShell.SendKeys("{Enter}")
Do
strFromProc = oExec.Stdout.Readline()
WScript.Echo strFromProc
Loop While Not objLogFile.StdOut.atEndOfStream
You can capture output from external commands but not at the same time interact with them like you do with sendkeys. Here an example of what works
Function ExecPing(strTarget)
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strTarget)
strPingResults = LCase(objExec.StdOut.ReadAll)
If InStr(strPingResults, "antwoord van") Then '"reply from" in E
WScript.Echo VbCrLf & strTarget & " responded to ping."
ExecPing = True
Else
WScript.Echo VbCrLf & strTarget & " did not respond to ping."
ExecPing = False
End If
End Function
ExecPing pcname

Resources