VBScript: How to change variable value by calling another script file? - vbscript

This is how I'm passing arguments between files these days.
1.vbs:
Dim MyVar
'1) Assigning some value to MyVar.
MyVar = "foo"
'2) Passing MyVar to 2.vbs.
CreateObject("WScript.Shell").Run _
Chr(34) & "C:" & "\2.vbs" & _
Chr(34) & " " & Chr(34) & MyVar & Chr(34), _
1, True
'4) End point.
MsgBox MyVar
2.vbs:
If _
WScript.Arguments.Count > 0 _
Then
Call MySub( _
WScript.Arguments(0))
End If
Sub MySub(MyVar)
'3) Doing some work with MyVar.
MyVar = "bar"
End Sub
So, if all code was in 1 single file, and
if I had to use Call MySub instead of CreateObject("WScript.Shell").Run
— i'd successfully changed MyVar from "foo" to "bar",
and got the latter on MsgBox.
Yet, sometimes I really want to work with MyVar in another file,
and be able to get it back (to the already running first file) with changes.
I just don't know how to do that properly.

Option 1:
keep the files as they are, and add an echo at the end of your sub:
2.vbs:
'(...)
'3) Doing some work with MyVar.
MyVar = "bar"
Wscript.Echo(MyVar)
'(...)
1.vbs
Read the output by changing the method ".Run" to ".Exec"
'(...)
'2) Passing MyVar to 2.vbs.
set oShell = CreateObject("Wscript.Shell")
set Exe = oShell.Exec("cmd /c 2.vbs """&MyVar&""" ")
MyVar = Exe.StdOut.ReadAll
'(...)
'4) End point.
MsgBox MyVar
Option 2:
Using the "2.vbs" file as a function library and changing the sub to function:
1.vbs
'Put the import statements at the top of 1.vbs code for easier readability.
Import "2.vbs"
'(...)
MyVar = MyFunction(MyVar)
2.vbs
Function MyFunction(MyVar)
'3) Doing some work with MyVar.
MyFunction = "bar"
end Function

Related

VBScript Higher-Order Functions

Is there a way to write anonymous functions, pass them to other functions, in which they are invoked, in vbscript?
There are no anonymous functions/subs/methods in VBScript.
You can use GetRef() (see sample1, sample2) to get something like a function pointer that can be passed to functions/subs to be invoked there (callback). But there are no closures in VBScript, so tricks possible in other languages fail in VBScript.
For specific problems that can be solved with higher order functions in functional languages there may be (nearly) equivalent VBScript solutions involving classes/objects; but for discussing that approach you need to describe your/such a problem in detail.
VBScript has the ability to execute arbitatry code.
Execute and Eval just do what they say to a string containing code.
ExecuteGlobal adds code to your program, like a new function, new variables.
Script Control adds vbscript/jscript scripting language to any program including vbscripts. It can have access to the host's data.
If using ExecuteGlobal/Execute/Eval it is best to run through a scriptcontrol first to test for syntax errors (as you can't trap syntax errors, but you can trap the runtime error the script control gives off on a syntax error).
So you can build your program at runtime.
Set Arg = WScript.Arguments
set WshShell = createObject("Wscript.Shell")
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout
Sub VBSCmd
RawScript = LCase(Arg(1))
'Remove ^ from quoting command line and replace : with vbcrlf so get line number if error
Script = Replace(RawScript, "^", "")
Script = Replace(Script, "'", chr(34))
Script = Replace(Script, ":", vbcrlf)
'Building the script with predefined statements and the user's code
Script = "Dim gU" & vbcrlf & "Dim gdU" & vbcrlf & "Set gdU = CreateObject(" & chr(34) & "Scripting.Dictionary" & chr(34) & ")" & vbcrlf & "Function UF(L, LC)" & vbcrlf & "Set greU = New RegExp" & vbcrlf & "On Error Resume Next" & vbcrlf & Script & vbcrlf & "End Function" & vbcrlf
'Testing the script for syntax errors
On Error Resume Next
set ScriptControl1 = wscript.createObject("MSScriptControl.ScriptControl",SC)
With ScriptControl1
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.AddCode Script
End With
With ScriptControl1.Error
If .number <> 0 then
Outp.WriteBlankLines(1)
Outp.WriteLine "User function syntax error"
Outp.WriteLine "=========================="
Outp.WriteBlankLines(1)
Outp.Write NumberScript(Script)
Outp.WriteBlankLines(2)
Outp.WriteLine "Error " & .number & " " & .description
Outp.WriteLine "Line " & .line & " " & "Col " & .column
Exit Sub
End If
End With
ExecuteGlobal(Script)
'Remove the first line as the parameters are the first line
'Line=Inp.readline
Do Until Inp.AtEndOfStream
Line=Inp.readline
LineCount = Inp.Line
temp = UF(Line, LineCount)
If err.number <> 0 then
outp.writeline ""
outp.writeline ""
outp.writeline "User function runtime error"
outp.writeline "==========================="
Outp.WriteBlankLines(1)
Outp.Write NumberScript(Script)
Outp.WriteBlankLines(2)
Outp.WriteLine "Error " & err.number & " " & err.description
Outp.WriteLine "Source " & err.source
Outp.WriteLine "Line number and column not available for runtime errors"
wscript.quit
End If
outp.writeline temp
Loop
End Sub
Vbs
filter vbs "text of a vbs script"
filter vb "text of a vbs script"
Use colons to seperate statements and lines. Use single quotes in place of double quotes, if you need a single quote use chr(39). Escape brackets and ampersand with the ^ character. If you need a caret use chr(136).
The function is called UF (for UserFunction). It has two parameters, L which contains the current line and LC which contains the linecount. Set the results of the script to UF. See example.
There are three global objects available. An undeclared global variable gU to maintain state. Use it as an array if you need more than one variable. A Dictionary object gdU for saving and accessing previous lines. And a RegExp object greU ready for use.
Example
This vbs script inserts the line number and sets the line to the function UF which Filter prints.
filter vbs "uf=LC ^& ' ' ^& L"<"%systemroot%\win.ini"
This is how it looks in memory
Dim gU
Set gdU = CreateObject("Scripting.Dictionary")
Set greU = New RegExp
Function UF(L, LC)
---from command line---
uf=LC & " " & L
---end from command line---
End Function
If there is a syntax error Filter will display debugging details.
User function syntax error
==========================
1 Dim gU
2 Dim gdU
3 Set greU = CreateObject("Scripting.Dictionary")
4 Function UF(L, LC)
5 On Error Resume Next
6 uf=LC dim & " " & L
7 End Function
Error 1025 Expected end of statement
Line 6 Col 6
User function runtime error
===========================
1 Dim gU
2 Dim gdU
3 Set greU = CreateObject("Scripting.Dictionary")
4 Function UF(L, LC)
5 On Error Resume Next
6 uf=LC/0 & " " & L
7 End Function
Error 11 Division by zero
Source Microsoft VBScript runtime error
Line number and column not available for runtime errors
the funny thing about function objects is that they by definition are a memory leak. This means that once you create a function object, you need to keep the scope it was created in intact, which threw me off.
Class VBCompiler
Public leaks
Public Sub Class_Initialize()
leaks = Array()
End Sub
Public Function Compile(code)
Dim compiler, result
Set compiler = CreateObject("MSScriptControl.ScriptControl")
Set portal = CreateObject("Scripting.Dictionary")
Dim name
compiler.Language = "VBScript"
compiler.AddObject "portal", portal, True
compiler.ExecuteStatement code
name = compiler.Procedures(1).Name
compiler.ExecuteStatement "portal.Add ""result"", GetRef(""" & name & """)"
' save the script control because if we go out of scope...
' our function object goes poof!
' leaks.Push compiler
ReDim Preserve leaks(UBound(leaks) + 1)
Set leaks(UBound(leaks)) = compiler
Set Compile = portal("result")
End Function
End Class
Dim z
Set z = New VBCompiler
Set z2 = z.Compile("Function Foo(s):MsgBox s:Foo = 2:End Function")
z2("Hi!")
z2 "Hello Again!"
Gives the two message boxes as desired
Class VBCompiler
Public Function Compile(code)
Dim compiler, result
Set compiler = CreateObject("MSScriptControl.ScriptControl")
Set portal = CreateObject("Scripting.Dictionary")
Dim name
compiler.Language = "VBScript"
compiler.AddObject "portal", portal, True
compiler.ExecuteStatement code
name = compiler.Procedures(1).Name
compiler.ExecuteStatement "portal.Add ""result"", GetRef(""Foo"") "
Set Compile = portal("result")
End Function
End Class
Dim z
Set z = New VBCompiler
Set z2 = z.Compile("Function Foo():MsgBox ""Well Met!"":Foo = 2:End Function")
z2("Hi!")
z2 "Hello Again!"
The above gives (29, 5) (null): Unspecified error. This error is in essence: your object has committed suicide.
This approach can be improved(in particular, the issue of wasteful one ScriptControl per compilation without any plans to release them).

Vbscript start vbs with arguments and define multiple arguments

I need to start a vbs script by an argument and related to the passed argument see a pop up.
Example :
Dim Arg, var1, var2
Set Arg = WScript.Arguments
'Parameter1, begin with index0
var1 = Arg(0)
if (instr(WScript.Arguments.Name,"Printer")> 0 then
wscript.echo "Printer type..."
end if
if (instr(WScript.Arguments.Name,"help")> 0 then
wscript.echo "help..."
end if
Thanks in advance
'Clear the objects at the end of your script.
set Arg = Nothing
call you script like so
myscript.vbs /help
and access args like so
'setup the named argument collection
set argNamedCollection = WScript.Arguments.Named
'get the arguments passed in
argHelp = argNamedCollection.Item("help")
argPrinter = argNamedCollection.Item("printer")
'or check directly
'check for help arguments
if argNamedCollection.Exists("help") then
'do somthing
end if

VBScript how to join WScript.Arguments?

I am trying to join the arguments to a string to be passed to another script. The following:
WScript.Echo(Join(WScript.Arguments))
gives me an error:
Error: Wrong number of arguments or invalid property assignment
Code: 800A01C2
What is wrong with that syntax?
WshArgument objects are not arrays, so you can't use Join() on them. What you can do is something like this:
ReDim arr(WScript.Arguments.Count-1)
For i = 0 To WScript.Arguments.Count-1
arr(i) = WScript.Arguments(i)
Next
WScript.Echo Join(arr)
Another solution can be done with ArrayList object from the system:
Set oAL = CreateObject("System.Collections.ArrayList")
For Each oItem In Wscript.Arguments: oAL.Add oItem: Next
WScript.Echo Join(oAL.ToArray, " ")
ReDim arr(WScript.Arguments.Count-1)
For i = 0 To WScript.Arguments.Count-1
arr(i) = """"+WScript.Arguments(i)+""""
Next
WScript.Echo Join(arr)
this will add quotes for each argument,
you can then remove it in the batch file with %~1 and so on.
Here is the function that I use. It will return all the arguments whether they contain quotes or not in a string that you can pass to another script.
Function GetArguments()
Dim Args, Arg
If WSH.Arguments.Count > 0 Then
For Each Arg In WSH.Arguments
Args = Args & """" & Arg & """ "
Next
Args = " """"" & Trim(Args) & """"""
End If
GetArguments = Args
End Function

Passing-variable-from-vbscript-to-batch-file with arguments

Please how to pass the 'inp" variable from this piece of vbs to my batch named job.bat? Indeed when doing echoing (echo %2) from job.bat, i notice that the inp is not passed properly. prompt command views inp and not the value retrieved from vbs. Thanks
For Each listElement In xmlDoc.selectNodes("document/Lists/list")
msgbox "toto"
inp=listElement.selectSingleNode("entry").text
out= listElement.selectSingleNode("output").text
jeton= listElement.selectSingleNode("token").text
dim shell
set shell=createobject("wscript.shell")
shell.run "job.bat ""a file"" **inp** "
set shell=nothing
Next
I think what you're looking for is this.
shell.run "job.bat ""argfile.ext"" " & inp
However, as Ansgar Wiechers points out, this is a potentially severe security hole, as a treacherously crafted XML file could run arbitrary commands. To encapsulate your batch file arguments and prevent unintended consequences, consider switching to the Shell.Application object's ShellExecute method.
For Each listElement In xmlDoc.selectNodes("document/Lists/list")
msgbox "toto"
inp = listElement.selectSingleNode("entry").text
out = listElement.selectSingleNode("output").text
jeton = listElement.selectSingleNode("token").text
set shell=CreateObject("Shell.Application")
shell.ShellExecute "job.bat", """a file"" " & inp, "path\to\batfile\", "runas", 1
set shell=nothing
Next
Unlike several other languages VBScript doesn't expand variables inside strings. Because of that, inp in the string
"job.bat ""a file"" inp "
is just the literal string "inp", not the value of the variable inp. To produce a string with the value of a variable, you have to concatenate base string and variable like #rojo suggested:
shell.run "job.bat ""a file"" " & inp
I would, however, not recommend doing this without some safety precautions. For one thing you should always put double quotes around your arguments, in case they contain spaces. I normally use a quoting function for this to prevent the instruction from becoming riddled with quad-quotes:
Function qq(str) : qq = Chr(34) & str & Chr(34) : End Function
'...
shell.run "job.bat " & qq("a file") & " " & qq(inp)
You should also always apply sanitizing to all user input that is passed to a shell command. Otherwise your users might wreak havoc by entering something like foo & del /s /q C:\*.*. Common practice is to allow only known-good characters in the input string and replace everything else with a safe character (e.g. an underscore). You can achieve this with a regular expression:
Set re = New RegExp
re.Pattern = "[^ a-z0-9äöü.,_$%()-]"
re.Global = True
re.IgnoreCase = True
inp = re.Replace(inp, "_")

Force a VBS to run using cscript instead of wscript

What is the stackoverflow approved (and hence correct) method to force a VBS to run using cscript instead of wscript - irrespective of what the user tries?
A quick Google search shows plenty of examples, but some of them simply don't work and those which do often don't handle the fact that it may have been run with arguments so I'm keen to know what the best way is.
Here is one example which doesn't handle arguments:
sExecutable = LCase(Mid(Wscript.FullName, InstrRev(Wscript.FullName,"\")+1))
If sExecutable <> "cscript.exe" Then
Set oShell = CreateObject("wscript.shell")
oShell.Run "cscript.exe """ & Wscript.ScriptFullName & """"
Wscript.Quit
End If
I appreciate that this could probably be easily modified to handle arguments, but realise that this may not be the best way to approach the problem.
Background: I'm writing a script which can run by double clicking or (most likely) from either a DOS batch file or as a scheduled task. It can contain one or more optional command line arguments.
My Lord, what unadulterated rubbish. It makes me cry to see such cruddy coding (no offense to anybody, lol). Seriously, though, here's my 2 pence:
Sub forceCScriptExecution
Dim Arg, Str
If Not LCase( Right( WScript.FullName, 12 ) ) = "\cscript.exe" Then
For Each Arg In WScript.Arguments
If InStr( Arg, " " ) Then Arg = """" & Arg & """"
Str = Str & " " & Arg
Next
CreateObject( "WScript.Shell" ).Run _
"cscript //nologo """ & _
WScript.ScriptFullName & _
""" " & Str
WScript.Quit
End If
End Sub
forceCScriptExecution
It handles arguments, AND checks for spaces in said arguments -- so that in the case of a filename passed to the original script instance that contained spaces, it wouldn't get "tokenized" when passed to cscript.exe.
Only thing it doesn't do is test for StdIn (e.g., in the case where someone piped something to the script via the command line, but forgot to use "cscript script.vbs") -- but if it was executed by WScript.exe, WScript.StdIn's methods all return Invalid Handle errors, so there's no way to test that anyway.
Feel free to let me know if there's a way to "break" this; I'm willing to improve it if necessary.
Two small additions to forceCScriptExecution let me see its Window after termination and handle its return code.
Sub forceCScriptExecution
Dim Arg, Str
If Not LCase( Right( WScript.FullName, 12 ) ) = "\cscript.exe" Then
For Each Arg In WScript.Arguments
If InStr( Arg, " " ) Then Arg = """" & Arg & """"
Str = Str & " " & Arg
Next
**ret =** CreateObject( "WScript.Shell" ).Run **("cmd /k** cscript //nologo """ & WScript.ScriptFullName & """ " & Str**,1,true)**
WScript.Quit **ret**
End If
End Sub
Notes: "cmd /k" let the windows stay after execution. Parameter "1" activates the window. Parameter "true" waits for termination, so variable "ret" can return the error code.
Here's a similar one in JScript for making .js files run in CScript:
(function(ws) {
if (ws.fullName.slice(-12).toLowerCase() !== '\\cscript.exe') {
var cmd = 'cscript.exe //nologo "' + ws.scriptFullName + '"';
var args = ws.arguments;
for (var i = 0, len = args.length; i < len; i++) {
var arg = args(i);
cmd += ' ' + (~arg.indexOf(' ') ? '"' + arg + '"' : arg);
}
new ActiveXObject('WScript.Shell').run(cmd);
ws.quit();
}
})(WScript);
WScript.echo('We are now in CScript. Press Enter to Quit...');
WScript.stdIn.readLine();
https://gist.github.com/4482361
One approach might be to give it another extension instead of .vbs. Say .cvbs for example. Associate .cvbs with cscript.exe not wscript.exe, that way executing or double clicking a .cvbs file will never invoke the wscript.exe.
Here is my code snippet i use for some of my scripts. It handles Arguments as well. All you have to do is replace the {EnterWorC} with either a "w" or "c" WITH quotes
Dim WorC, Command, Arguments, I
WorC={EnterWOrC} 'Make sure you replace "{EnterWOrC}" with a "w" or a "c" and BE SURE TO PUT QUOTES AROUND THE LETTER.
WorC=LCase (WorC)
If lcase (WorC)="w" Or lcase (WorC)="c" Then
If LCase (Right (WScript.FullName,11))<> WorC & "script.exe" Then
command=WScript.ScriptFullName
Arguments=""
For I=0 To UBound (WScript.Arguments)
Arguments=Arguments & Chr (34) & WScript.Arguments(I) & Chr (34) & Space (1)
Next
CreateObject("Wscript.Shell").Run WorC & "script.exe " & Chr (34) & command & Chr (34) & Space (1) & Arguments, 1
WScript.Quit
End If
WorC=Empty
Command=Empty
I=Empty
Arguments=Empty
End If
Here you will have to replace the 2nd line (2nd NON-blank line)
WorC={EnterWOrC} 'Make sure you replace "{EnterWOrC}" with a "w" or a "c" and BE SURE TO PUT QUOTES AROUND THE LETTER.
For Wscript: WorC="W"
For CScript: WorC="C"
It is NOT case Sensitive.

Resources