This question already has answers here:
Can I pass an argument to a VBScript (vbs file launched with cscript)?
(5 answers)
Closed 2 years ago.
I need help rendering input through 2 different VBScripts. Here's my code, but I need a way of rendering the input of A.vbs into B.vbs, here's my code:
Option Explicit
Dim Shell
Set Shell = CreateObject("WScript.Shell")
Speed = InputBox("How long do you have to wait between clicks, in seconds?", "")
Wait = InputBox("How long until this script runs?", "")
msgbox("You have " & Wait & " seconds until this script runs.")
WScript.Sleep (Wait*1000)
Shell.Run "B.vbs"
You can use Environment Variables:
' Create WSH Shell object
Dim objWshShell
Set objWshShell = CreateObject("WScript.Shell")
' Get the Environment
Dim objEnvironment
Set objEnvironment = objWshShell.Environment("System")
' Write to variable
objEnvironment("Speed") = Speed
' Read from variable
MsgBox objEnvironment("Speed")
You will want to write to the environment variable(s) in your A.vbs script and read from the variable(s) in your B.vbs script.
Related
i'm trying to help my little brother with a vbs script file, i've never used vbs, and i'm having serious issues on finding out how to end a bat file that i've opened with the vbs script after 2 seconds
I've tried terminate but it doesn't work, even running another shell with taskkill and the name of process but nothing
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "C:\\Users\me\Desktop\Samples\t.bat"
Wscript.Sleep 2000`
I would like the bat file to close itself after 2 seconds
Use the Exec command instead of Run.
https://ss64.com/vb/exec.html
"Unlike .Run method, .Exec returns an object which returns additional information about the process started."
This example uses cmd.exe /k (the /k will keep the cmd.exe window open, which will be killed after your 2 second timeout even if your bat script logic finishes before that)
Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("cmd.exe /k C:\Temp\test.bat") : wscript.sleep 2000 :
Rt.Terminate
If you want to return the output of the bat script you will need to read this WScript.Shell.Exec - read output from stdout, and use logic similar to:
Const WshRunning = 0
Const WshFinished = 1
Const WshFailed = 2
strCommand = "C:\Temp\test.bat"
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec(strCommand)
Do While oExec.Status = 0
WScript.Sleep 1000
If Not oExec.StdErr.AtEndOfStream Then
vErrStr = vErrStr & oExec.StdErr.ReadAll
End If
If Not oExec.StdOut.AtEndOfStream Then
vOutStr = vOutStr & oExec.StdOut.ReadAll
End If
Loop
WScript.StdOut.Write(vErrStr)
WScript.Echo(vOutStr)
It all depends on what your bat file is doing really, and the reason you need to kill it after x seconds.
Edit:
Because your batch file is a continuous loop, it may confuse ReadAll of the output stream. You might be best using something such as (note that you will not see real-time output):
Dim strCommand : strCommand = "C:\Temp\test.bat"
Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
'execute command
Dim oExec : Set oExec = WshShell.Exec(strCommand)
'wait 2 seconds
WScript.Sleep 2000
'terminate command
oExec.terminate
'get output
wscript.echo oExec.StdOut.ReadAll
Set oExec = Nothing
Set WshShell = Nothing
This question already has an answer here:
How to get a path with the variable user in VBscript
(1 answer)
Closed 4 years ago.
I have been trying to get the below script to work with the current user that's logged on:
On Error Resume Next
Set oFileSys = WScript.CreateObject("Scripting.FileSystemObject")
sRoot = "C:\users\MyUsername\downloads"
today = Date
nMaxFileAge = 30
DeleteFiles(sRoot)
Function DeleteFiles(ByVal sFolder)
Set oFolder = oFileSys.GetFolder(sFolder)
Set aFiles = oFolder.Files
Set aSubFolders = oFolder.SubFolders
For Each file in aFiles
dFileCreated = FormatDateTime(file.DateCreated, "2")
If DateDiff("d", dFileCreated, today) > nMaxFileAge Then
file.Delete(True)
End If
Next
For Each folder in aSubFolders
DeleteFiles(folder.Path)
Next
End Function
Now this works fine when I specifically define the "MyUsername" part of sRoot=, but I want this to be a variable. I have tried many suggestions in other posts but just can't seem to get this to work.
I'm going to deploy this to a few machines on startup that have different users so that's why it needs to be a variable as I don't know who will be logged into those computers at any given time.
From Help
Returns an environment variable's expanded value.
object.ExpandEnvironmentStrings(strString)
object
WshShell object.
str
String
String value indicating the name of the environment variable you want to expand.
The ExpandEnvironmentStrings method expands environment variables
defined in the PROCESS environment space only. Environment variable
names, which must be enclosed between "%" characters, are not
case-sensitive.
The following code expands the Windows Directory environment variable
and displays it:
Visual Basic Script
set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%WinDir%")
The preferred way is to
Returns the name of a user.
object.UserName
object
WshNetwork object.
*Returns a string.*
If you are using this property in a login script, see Creating an
Automated Login Script.
The following example demonstrates the use of the UserName property:
Set WshNetwork = WScript.CreateObject("WScript.Network")
WScript.Echo "Domain = " & WshNetwork.UserDomain
WScript.Echo "Computer Name = " & WshNetwork.ComputerName
WScript.Echo "User Name = " & WshNetwork.UserName
I have discovered the answer in the following article:
How to get a path with the variable user in VBscript
In short for anyone else needing this, here is the corrected code (for my example):
On Error Resume Next
Set oShell = CreateObject( "WScript.Shell" )
userprofile = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
Set oFileSys = WScript.CreateObject("Scripting.FileSystemObject")
sRoot = userprofile & "\downloads"
today = Date
nMaxFileAge = 2
Thanks.
Set sh = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim counter, myNum, fileLine
myNum = 0
counter = 9000000
Do While myNum < counter
myNum = myNum + 1
Call GetConnections()
Loop
Function GetConnections()
i = 0
outFile = "netband_logger_vbs.tmp"
Set objFile = objFSO.CreateTextFile(outFile, True)
Set shExec = sh.Exec("netstat -e")
Do While Not shExec.StdOut.AtEndOfStream
fileLine = shExec.StdOut.ReadLine()
objFile.Write fileLine & vbCrLf
objFile.Close
Loop
End Function
I have the VBScript above. What I want to do is to run the netstat -e command 9000000 times and write every line of output to a text file line by line. And each time the after the first round of executions have terminated the script should overwrite the previous content of the netband_logger_vbs.tmp file with the values from the new round of executions.
Currently I have two problems: I can't seem to write the entire output to my .tmp file and I am also faced with an "object variable not set" error.
The error you're getting is probably because you're closing the file handle after the first iteration. To fix this move the line objFile.Close after the loop.
With that said, I wouldn't recommend using the Exec method here anyway. In your scenario it's much easier to shell out to CMD and use output redirection:
sh.Run "%COMSPEC% /c netstat -e >""" & outFile & """", 0, True
As for why you can't get all the entire output into one file; the FAT32 filesystem has a 4GB cap, and if you're writing lot's of small .tmp files there's a directory cap.
And to prevent the file from being closed during a lapse in the StdOut stream move objFile.Close to after the Loop
How do I pass and return arguments from a VBScript WITHOUT using cscript.exe?
For example, I want to call script2 from script1 that returns a value to script1 without any involvement of cscript.exe.
I have searched various answers but they somehow involve the usage of cscript.exe.
This script gets installed voices and sets the one provided in the file voice.txt.
Set WshShell = CreateObject("WScript.Shell")
WShShell.CurrentDirectory = "..\Confirmatory Texts"
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists("voice.txt") Then
Set temp = FSO.OpenTextFile("voice.txt")
confirm_voice = temp.ReadLine()
temp.Close
Set Sapi = CreateObject("SAPI.SpVoice")
For Each Voice In Sapi.GetVoices
i = i + 1
Next
For loopvar = 0 To i-1
If loopvar = CInt(confirm_voice) Then
Set Sapi.Voice = Sapi.GetVoices.Item(loopvar)
End If
Next
Else
WScript.Echo "An Error Occured"
End If
If I call this script from another script, how can I make this script to return some value to the script that invoked it?
VBScript doesn't really provide call or import mechanisms for other VBScript files. The closest thing is to read the contents of the other file and run them via ExecuteGlobal.
Demonstration:
Put the following two files in the same directory and run script1.vbs. It will read the contents of script2.vbs and make the function Square available in the global scope by running the code via ExecuteGlobal. Once the function is available in the global scope you it can be used in the rest of the script.
script1.vbs:
Set fso = CreateObject("Scripting.FileSystemObject")
dir = fso.GetParentFolderName(WScript.ScriptFullName)
script = fso.BuildPath(dir, "script2.vbs")
ExecuteGlobal fso.OpenTextFile(script).ReadAll '"import" code into global scope
WScript.Echo Square(3)
script2.vbs:
Function Square(i)
Square = i*i
End Function
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Vbscript - Read ini or text file for specific section
I am trying to check whether IPaddress of other PC can be accessed or not.
If IPaddress is static, following code is ok.
vbscript code
Dim Shell, strCommand, strHost, ReturnCode
strHost = "192.168.10.1"
Set Shell = wscript.createObject("wscript.shell")
strCommand = "ping -n 1 -w 300 " & strHost
ReturnCode = Shell.Run(strCommand, 0, True)
If ReturnCode = 0 Then
wscript.echo strHost & " is pingable"
Else
wscript.echo strHost & " is not pingable"
End If
As I want to check dynamic IPaddress, use ini file.
ini file
[IPaddress]
IP001 = "192.168.10.1";
IP002 = "192.168.10.2";
Now, I would like to know how to connect ini file and vbscript code.
Please explain it to me.
As Shadow Wizard mentions in his comment, you'll need to use FSO (FileSystemObject) to read the file. The sample code for OpenTextFile would probably be a good place to begin.
If you move your current vbscript code into a Sub that accepts one ip address as the argument you can just call that sub for each ip address in the file.
Maybe something like this (completely untested code):
Const ForReading = 1
Set MyFile = fso.OpenTextFile(FileName, ForReading)
Do While MyFile.AtEndOfStream <> True
line = MyFile.ReadLine
If Left(line, 2) = "IP" Then
ipAddress = Replace(Replace(Right(line, 8), ";", ""), """", "")
YourSubThatPings ipAddress
End If
Loop
MyFile.Close
The code that gets out the ipAddress from the line probably needs to be rewritten to be a bit more flexible though. And if the ini file contains a lot of other data maybe you need to add some code to skip to the correct section etc.