VBScript using variables value - vbscript

I am trying to run a VBScript which opens a program with elevated privileges and also pass it parameters.
Set oShell = CreateObject("Shell.Application")
Dim path = "app.exe"
If WScript.Arguments.Count = 1 Then
path = path & WScript.Arguments(0)
End If
oShell.ShellExecute path, , , "runas", 1
I get an error in the 2nd line. I tried using As String but that also didn't work.
Any ideas?

You are not allowed to declare a variable and set a value at the same time. Try this syntax instead.
Dim path
path = "app.exe"
or alternatively:
Dim path : path = "app.exe"
Where is the object WScript coming from? I don't see it initialized.
A great 'feature' to turn on is Option Explicit. When activated you must explicitly declare all variables by using the Dim or ReDim statements. If you try to use an undeclared variable name, an error occurs at compile time. This makes it easier to spot problems.

Related

Dynamically opening a website with VB script based on the website's IP address [duplicate]

I have this script saved in "test.vbs":
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(workFolder &"\test.txt", 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
When I run the script I want to pass the value of the "workFolder" variable.
How can I do this? Can I do it? Something like "cscript test.vbs workFolder:'C:\temp\'" perhaps?
Bonus question: Is it neccessary to clean up the passed variable with "Set workFolder = Nothing" or does VBSCript do that automatically when it terminates? Maybe "Set File = Nothing" and "Set FSO = Nothing" is unneccessary also? Please let me know if you know the answer to both these questions.
You can use WScript.Arguments to access the arguments passed to your script.
Calling the script:
cscript.exe test.vbs "C:\temp\"
Inside your script:
Set File = FSO.OpenTextFile(WScript.Arguments(0) &"\test.txt", 2, True)
Don't forget to check if there actually has been an argument passed to your script. You can do so by checking the Count property:
if WScript.Arguments.Count = 0 then
WScript.Echo "Missing parameters"
end if
If your script is over after you close the file then there is no need to set the variables to Nothing. The resources will be cleaned up automatically when the cscript.exe process terminates. Setting a variable to Nothing usually is only necessary if you explicitly want to free resources during the execution of your script. In that case, you would set variables which contain a reference to a COM object to Nothing, which would release the COM object before your script terminates. This is just a short answer to your bonus question, you will find more information in these related questions:
Is there a need to set Objects to Nothing inside VBA Functions
When must I set a variable to “Nothing” in VB6?
Inside of VBS you can access parameters with
Wscript.Arguments(0)
Wscript.Arguments(1)
and so on. The number of parameter:
Wscript.Arguments.Count
Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.
So in your code you could have:
strFolder = Wscript.Arguments.Item(0)
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.
MS Technet examples
You can also use named arguments which are optional and can be given in any order.
Set namedArguments = WScript.Arguments.Named
Here's a little helper function:
Function GetNamedArgument(ByVal argumentName, ByVal defaultValue)
If WScript.Arguments.Named.Exists(argumentName) Then
GetNamedArgument = WScript.Arguments.Named.Item(argumentName)
Else
GetNamedArgument = defaultValue
End If
End Function
Example VBS:
'[test.vbs]
testArg = GetNamedArgument("testArg", "-unknown-")
wscript.Echo now &": "& testArg
Example Usage:
test.vbs /testArg:123
To answer your bonus question, the general answer is no, you don't need to set variables to "Nothing" in short .VBS scripts like yours, that get called by Wscript or Cscript.
The reason you might do this in the middle of a longer script is to release memory back to the operating system that VB would otherwise have been holding. These days when 8GB of RAM is typical and 16GB+ relatively common, this is unlikely to produce any measurable impact, even on a huge script that has several megabytes in a single variable. At this point it's kind of a hold-over from the days where you might have been working in 1MB or 2MB of RAM.
You're correct, the moment your .VBS script completes, all of your variables get destroyed and the memory is reclaimed anyway. Setting variables to "Nothing" simply speeds up that process, and allows you to do it in the middle of a script.

How do I add %USERNAME% in a path while creating a txt file in VBS?

I'm coding a new VBS script, which should create a TXT file in the Documents directory. While with other inputs I used %USERNAME% for the User Name of the PC, the command "CreateTextFile" seems to want the real directory, without including any variables like %USERNAME%.
I'm kinda of new to this so I can't figure it out.
That's what I tried:
Dim objFS, objFile
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.CreateTextFile("C:\Users\%USERNAME%\Documents\Demo.txt", true)
objFile.WriteLine("some sample text")
It should understand %USERNAME% as the UserName of the PC, but doesn't.
What I get as result is the program saying he can't find the directory C:\Users\%USERNAME%\Documents.
To get the desktop one uses
SpecialFolders Property
Returns a SpecialFolders object (a collection of special folders).
object.SpecialFolders(objWshSpecialFolders)
Arguments
object WshShell object.
objWshSpecialFolders The name of the special folder. (eg Desktop)
Environment strings are not expanded. You can pass an entire string containing environmental variables. EG "%userprofile%\Desktop". This code lists all variables available https://pastebin.com/rrEyVxFd.
ExpandEnvironmentStrings Method
Returns an environment variable's expanded value.
object.ExpandEnvironmentStrings(strString)
Arguments
object WshShell object.
strString String value indicating the name of the environment variable
you want to expand.
There are plenty longer drawn-out, which are appropriate but these are a couple examples - much easier:
Option Explicit
Msgbox CreateObject("WScript.Network").UserName
' or into a variable
Dim oShell : set oShell = CreateObject("WScript.Network")
Dim UserName : UserName = oShell.UserName
Msgbox UserName
Set oShell = Nothing

ShellExecute raises type mismatch error when trying to open a file

I am trying to automate a .application file to open automatically on an end users machine. The code I found online says to do this:
Dim my_file
my_file = "c:/location/example.application"
ShellExecute 0, vbNullString, my_file, vbNullString, vbNullString, vbNormalFocus
but when I try to run it I get a type mismatch error on line 4 which is the ShellExecute line. How can I fix this?
ShellExecute() is a method of a Shell Application object. You'll need to create an instance of the class before you can call one of its methods:
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute my_file
Most of the parameters to ShellExecute() are optional and can be omitted, if you'd like.
See this page for information.
Also note that constants defined by external type libraries (as is the case here) are not immediately available to VBScript. That means your script will not understand vbNormalFocus. The easiest way to overcome this is to just define the constants yourself.
Const vbNormalFocus = 1

VBS WScript.Run fails after passing Exists test

In a couple of place in my code I check if the file exists (it does) then I try to Run the file as above, or get the DateLastModified, and get errors about file not found or invalid path. How can the script NOT see a file after confirming it exists?
I'm working up a .vbs script that tries to run an Access .mdb file. The WScript.Run command seems to choke on the filename, but putting a MsgBox() before that call to display the path allows Run to work properly. I don't want to display a popup.
Error is:
The directory name is invalid.
How is this possible and how can I get around it?
Here is code:
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
SET ws = WScript.CreateObject("WScript.Shell")
path = Chr(34) & LocalPath & AccessFileName & Chr(34)
if (fso.FileExists(LocalPath & AccessFileName)) THEN
'MsgBox(path) 'Uncommenting this line removes the error
ws.Run path 'This line errors
End If
Try to open your file with shell .InvokeVerb method:
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
If CreateObject("Scripting.FileSystemObject").FileExists(LocalPath & AccessFileName) Then
CreateObject("Shell.Application").Namespace(LocalPath).ParseName(AccessFileName).InvokeVerb
End If
UPD: Both ActiveX WScript.Shell and Shell.Application uses native windows shell to perform a file execution.The first one launches new process via WSH core located in wscript.exe, cscript.exe, wshom.ocx, jscript.dll, vbscript.dll, ets, .Run and .Exec methods of WsShell object provides wide control on the launched process, and second one located in Shell32.dll, uses .InvokeVerb method of IShellDispatch object, called without name, runs default verb equals to the windows explorer "open" command.In case of any issues connected to WSH, explorer might still works without any proplems. If it does, that is just a work-around, I can't say what's wrong definetely without close look.
Hello the following code worked for me.
Basically this code gets a folder object and loops through all files in a folder and checks if its the one that you named. This it runs the application.
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = Wscript.CreateObject("Wscript.Shell")
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
Set myFolder = fso.GetFolder(LocalPath)
For each myFile in myFolder.Files
If myFile.Name = AccessFileName Then
'Wscript.Echo myFile.Name
ws.Run myFolder.Path & "\" & myFile.Name
End If
Next
You can give this a shot. You probably do not need the quotes around the path, but I included it as a comment if you want to give it a shot. You just put quotes twice if you need to include a quote character in a string:
Set fso = CreateObject("Scripting.FileSystemObject")
AccessFileName = "App.mdb"
LocalPath = "C:\Folder\"
Set ws = WScript.CreateObject("WScript.Shell")
' path = """" & LocalPath & AccessFileName & """" <-- probably unnecessary
path = LocalPath & AccessFileName
If (fso.FileExists(path)) Then
Set file = fso.GetFile(path)
'MsgBox(path) 'Uncommenting this line removes the error
ws.Run file.Path 'This line errors
End If
This does not make any sense. Having a MsgBox line is altering the behavior of the program!!!
I feel it is probably some weird invisible character somewhere which is getting activated when you comment the line.
Try retyping the If block without the MsgBox in between.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

I have this script saved in "test.vbs":
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(workFolder &"\test.txt", 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
When I run the script I want to pass the value of the "workFolder" variable.
How can I do this? Can I do it? Something like "cscript test.vbs workFolder:'C:\temp\'" perhaps?
Bonus question: Is it neccessary to clean up the passed variable with "Set workFolder = Nothing" or does VBSCript do that automatically when it terminates? Maybe "Set File = Nothing" and "Set FSO = Nothing" is unneccessary also? Please let me know if you know the answer to both these questions.
You can use WScript.Arguments to access the arguments passed to your script.
Calling the script:
cscript.exe test.vbs "C:\temp\"
Inside your script:
Set File = FSO.OpenTextFile(WScript.Arguments(0) &"\test.txt", 2, True)
Don't forget to check if there actually has been an argument passed to your script. You can do so by checking the Count property:
if WScript.Arguments.Count = 0 then
WScript.Echo "Missing parameters"
end if
If your script is over after you close the file then there is no need to set the variables to Nothing. The resources will be cleaned up automatically when the cscript.exe process terminates. Setting a variable to Nothing usually is only necessary if you explicitly want to free resources during the execution of your script. In that case, you would set variables which contain a reference to a COM object to Nothing, which would release the COM object before your script terminates. This is just a short answer to your bonus question, you will find more information in these related questions:
Is there a need to set Objects to Nothing inside VBA Functions
When must I set a variable to “Nothing” in VB6?
Inside of VBS you can access parameters with
Wscript.Arguments(0)
Wscript.Arguments(1)
and so on. The number of parameter:
Wscript.Arguments.Count
Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.
So in your code you could have:
strFolder = Wscript.Arguments.Item(0)
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.
MS Technet examples
You can also use named arguments which are optional and can be given in any order.
Set namedArguments = WScript.Arguments.Named
Here's a little helper function:
Function GetNamedArgument(ByVal argumentName, ByVal defaultValue)
If WScript.Arguments.Named.Exists(argumentName) Then
GetNamedArgument = WScript.Arguments.Named.Item(argumentName)
Else
GetNamedArgument = defaultValue
End If
End Function
Example VBS:
'[test.vbs]
testArg = GetNamedArgument("testArg", "-unknown-")
wscript.Echo now &": "& testArg
Example Usage:
test.vbs /testArg:123
To answer your bonus question, the general answer is no, you don't need to set variables to "Nothing" in short .VBS scripts like yours, that get called by Wscript or Cscript.
The reason you might do this in the middle of a longer script is to release memory back to the operating system that VB would otherwise have been holding. These days when 8GB of RAM is typical and 16GB+ relatively common, this is unlikely to produce any measurable impact, even on a huge script that has several megabytes in a single variable. At this point it's kind of a hold-over from the days where you might have been working in 1MB or 2MB of RAM.
You're correct, the moment your .VBS script completes, all of your variables get destroyed and the memory is reclaimed anyway. Setting variables to "Nothing" simply speeds up that process, and allows you to do it in the middle of a script.

Resources