When creating multiple environment variables references are not being expanded - vbscript

When creating multiple environment variables in sequence using VBS, the earlier variables are never getting expanded when referenced in the later variables.
Set wshUserEnv = objShell.Environment( "USER" )
wshUserEnv("A") = "a"
wshUserEnv("b") = "%A%\b"
Then,
objShell.ExpandEnvironmentStrings(GetEnvVariable("b"))
does not give the value of a\b, but, instead stays as %A%\b
Also, listing the values from command line prints the same value. But, once the variable is edited (minor edit like adding a semicolon) from System Properties dialog, the variable gets expanded.
GetEnvVariable is a helper function:
Function GetEnvVariable (EnvVariable)
Dim wshUserEnv
Set wshUserEnv = objShell.Environment( "USER" )
GetEnvVariable=wshUserEnv(EnvVariable)
End Function

Regarding .ExpandEnvironmentStrings() behavior:
Run the first script below:
Set objShell = CreateObject("WScript.Shell")
' set values to variables
objShell.Environment("user")("user___var") = "user___value"
objShell.Environment("process")("process___var") = "process___value"
objShell.Environment("system")("system___var") = "system___value"
objShell.Environment("volatile")("volatile___var") = "volatile___value"
s = "check accessibility within running script process" & vbCrLf
s = s & objShell.ExpandEnvironmentStrings("%user___var%") & vbCrLf
s = s & objShell.ExpandEnvironmentStrings("%process___var%") & vbCrLf
s = s & objShell.ExpandEnvironmentStrings("%system___var%") & vbCrLf
s = s & objShell.ExpandEnvironmentStrings("%volatile___var%") & vbCrLf
WScript.Echo(s)
objShell.Run "cmd.exe /k echo check accessibility within child process & echo %user___var% & echo %process___var% & echo %system___var% & echo %volatile___var%"
The output will be the same for both WScript.Echo and cmd.exe /k echo:
%user___var%
process___value
%system___var%
%volatile___var%
After that run the second script:
Set objShell = CreateObject("WScript.Shell")
s = "check accessibility via another script process" & vbCrLf
s = s & objShell.ExpandEnvironmentStrings("%user___var%") & vbCrLf
s = s & objShell.ExpandEnvironmentStrings("%process___var%") & vbCrLf
s = s & objShell.ExpandEnvironmentStrings("%system___var%") & vbCrLf
s = s & objShell.ExpandEnvironmentStrings("%volatile___var%") & vbCrLf
WScript.Echo(s)
objShell.Run "cmd.exe /k echo check accessibility via another script process & echo %user___var% & echo %process___var% & echo %system___var% & echo %volatile___var%"
The output will be:
user___value
%process___var%
system___value
volatile___value
I've checked behavior on Win7 x64 and VirtualBox WinXP. As you can see, process environment is only accessible for .ExpandEnvironmentStrings() within running process or via child process, that first script shows. Other environments are not accessible for .ExpandEnvironmentStrings() until running script (in which variables were set) finishes. When you run second script, you become able to read all environments variables via .ExpandEnvironmentStrings(), except process.
I hope this explanation will help to get your code to work.
The code you show objShell.ExpandEnvironmentStrings(GetEnvVariable("b")) gives you %A%\b because GetEnvVariable("b") returns %A%\b (.Environment() method implemented in the function has access to user environment, and all others environments, but it doesn't process contained %A% as variable statement, as .ExpandEnvironmentStrings() does), and then .ExpandEnvironmentStrings("%A%\b") returns the value without any changes (the method has no access to A variable in user environment till script termination).

Related

Use VBS to run a program with parameters

I'm a total vbs novice trying to perform the supposedly simple task of using a vbscript to run a single program (with parameters).
The path the to program is:
C:\Program Files (x86)\SpeedyFox\speedyfox.exe
and the parameter switch that must go with it is:
/Firefox:C:\Program Files\Firefox\Data\profile
If I wrap both sections in quotes (due to the spaces in their paths) it gives the following combined single command:
"C:\Program Files (x86)\SpeedyFox\speedyfox.exe" "/Firefox:C:\Program Files\Firefox\Data\profile"
If I then paste this into Start > Run it works exactly as I want.
I'm just trying to achieve the same thing from a vbs script instead of manually pasting into the Run box.
I do not want the command to run within a CMD console (as other questions on here have asked). All I am trying to do is to get "C:\Program Files (x86)\SpeedyFox\speedyfox.exe" "/Firefox:C:\Program Files\Firefox\Data\profile" to work with the shell.ShellExecute line of the script below.
Set objShell = Wscript.CreateObject ("Wscript.shell")
set shell=CreateObject("Shell.Application")
shell.ShellExecute ** WHAT DO I PUT HERE? **
set shell=nothing
but try as I might, I just keep getting WSH "Expected end of statement" error messages.
1.First : I recommend you Make it a habit to use this quote function
to make it easy for you to quote variables in these situations !
2. Second : You should use MsgBox or Wscript.echo in order to show
and debug your variables easily !
Wscript.echo DblQuote("Hello World !")
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
So, I downloaded this application (speedyfox.exe) and i tested it on my Windows 10 (32bits)
So, here is what i tested and it works like a charm on my side :
Option Explicit
Dim objShell,MyCommand,strProgramFiles,SpeedyFoxfile,Title
Title = "Execute SpeedyFox in Commandline"
Set objShell = CreateObject("Shell.Application")
strProgramFiles = GetProgramFilesPath()
SpeedyFoxfile = strProgramFiles & "\SpeedyFox\speedyfox.exe"
MsgBox "Without Double Quotes" & vbCrlf & SpeedyFoxfile,vbInformation,Title
MsgBox "With Double Quotes" & vbCrlf & DblQuote(SpeedyFoxfile),vbInformation,Title
MyCommand = "CD /D "& DblQuote(strProgramFiles &"\SpeedyFox\") &"&"& DblQuote(SpeedyFoxfile) & " " & DblQuote("/Firefox:default") & " " & DblQuote("/Chrome:Default")
MsgBox MyCommand,vbInformation,Title
Call Execute(MyCommand)
'-----------------------------------------
Function Execute(StrCmd)
Dim ws,MyCmd,Result
Set ws = CreateObject("wscript.Shell")
MyCmd = "CMD /K " & StrCmd & ""'
Result = ws.run(MyCmd,1,True)
Execute = Result
End Function
'-----------------------------------------
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'-----------------------------------------
Function GetProgramFilesPath()
Dim ws,OsType,strProgramFiles
Set ws = createObject("WScript.Shell")
OsType = ws.RegRead("HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE")
If OsType = "x86" then
strProgramFiles = ws.ExpandEnvironmentStrings("%PROGRAMFILES%")
elseif OsType = "AMD64" then
strProgramFiles = ws.ExpandEnvironmentStrings("%PROGRAMFILES(x86)%")
end if
GetProgramFilesPath = strProgramFiles
End Function
'-----------------------------------------
Sigh, reminds me of my vbscript days, now I use Ruby and it's just as simple as
´my_shell_command params´
However, back to your question: the shortest way to use ShellExecute is
CreateObject("Shell.Application").ShellExecute "application", "parameters", "dir", "verb", window
See this documentation for explanation of the parameters.
EDIT:
You have to pay attention at the quotes, they need to be passed to the shell also by using two quotes
eg CreateObject("Shell.Application").ShellExecute "C:\Program Files (x86)\SpeedyFox\speedyfox.exe", """/Waterfox:C:\Program Files\Waterfox\Data\profile"""

vbs/batch folder name with spacing issue

Im having an issue where i am trying to create shortcuts but the vbs script is cutting out when it reaches a space in the path.
i have had a look around but many of the ones i have seen deal with the string being in vbs not being passed from a batch file.
here is my code so you can get a better understanding
Batch File:
#echo off
set office7="C:\ProgramData\Microsoft\Windows\Start Menu\Strategix Programs\Office Programs"
mkdir %office7%
cscript "H:\Installation Batch Files\createLink.vbs" ""%office7%\Purchase Order Entry.lnk"" "\\192.168.0.7\Temp\stock\Porder10.exe" "T:\Stock"
pause
Vbs file:
Set oShell = CreateObject("WScript.Shell") Set args = WScript.Arguments
sShortcut = oShell.ExpandEnvironmentStrings("" & args.Item(0) & "") sTarget = args.Item(1) sStartIn = args.Item(2)
WScript.Echo "Shortcut: " & sShortcut WScript.Echo "Target: " & sTarget WScript.Echo "StartIn: " & sStartIn
Output:
Shortcut: C:\ProgramData\Microsoft\Windows\Start Menu\Strategix Programs\Office Programs\Purchase
Target: Order
StartIn: Entry.lnk
Batch part
#echo off
set "office7=C:\ProgramData\Microsoft\Windows\Start Menu\Strategix Programs\Office Programs"
mkdir "%office7%"
cscript "H:\Installation Batch Files\createLink.vbs" "%office7%\Purchase Order Entry.lnk" "\\192.168.0.7\Temp\stock\Porder10.exe" "T:\Stock"
pause
The "correct" way of dealing with quotes is not include them in the value. If later you need them, adding them is easy (look the mkdir command and the arguments), but removing them is not. Without a good reason, do not include them. So, the "correct" way is
set "var=value"
That will assign the value to the variable, take care of problematic characters (all the assignation is inside quotes) and keep possible spaces at the end of the line out of the variable value.
Now, to the vbs part
Dim oShell
Set oShell = CreateObject("WScript.Shell")
Dim args
Set args = WScript.Arguments
Dim sShortcut, sTarget, sStartIn
sShortcut = args.Item(0)
sTarget = args.Item(1)
sStartIn = args.Item(2)
WScript.Echo "Shortcut: " & sShortcut
WScript.Echo "Target: " & sTarget
WScript.Echo "StartIn: " & sStartIn
There is no need for ExpandEnvironmentStrings, this has been done when the batch line was parsed in cmd. %office7% is a reference to the value of the variable, not the name of the variable, and the parser replaces variable reads with variable values.
And for the shortcut creation
With oShell.CreateShortcut( sShortcut )
.TargetPath = sTarget
.WorkingDirectory = sStartIn
.Save
End With

Starting a process in VBS: path not found

I need to make a simple vbs script to run some process' automatically. I found the following script on microsoft's website. It works fine to run notepad.exe the way the original example shows, but I'm trying to modify it to run myprog.exe. The full path to this program is: C:\myprogdir\myprog.exe
Const SW_NORMAL = 1
strComputer = "."
strCommand = "myprog.exe"
strPath = "C:\myprogdir\"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
' Configure the Notepad process to show a window
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = SW_NORMAL
' Create Notepad process
Set objProcess = objWMIService.Get("Win32_Process")
intReturn = objProcess.Create _
(strCommand, strPath, objConfig, intProcessID)
If intReturn <> 0 Then
Wscript.Echo "Process could not be created." & _
vbNewLine & "Command line: " & strCommand & _
vbNewLine & "Return value: " & intReturn
Else
Wscript.Echo "Process created." & _
vbNewLine & "Command line: " & strCommand & _
vbNewLine & "Process ID: " & intProcessID
End If
I keep getting Return value: 9, which indicates "Path Not Found". However the path is correct. Is there something I'm not getting?
You don't need all that to start a process, you just need the Shell object. Also, be sure to wrap the path of your executable in quotes (in case the path has spaces). Like this:
Option Explicit
Dim shl
Set shl = CreateObject("Wscript.Shell")
Call shl.Run("""C:\myprogdir\myprog.exe""")
Set shl = Nothing
WScript.Quit
Unless the path to your program is included in the system's %PATH% environment variable you need to specify the commandline with the full path to the executable. Specifying the path just as the working directory will not work.
strProgram = "myprog.exe"
strPath = "C:\myprogdir"
Set fso = CreateObject("Scripting.FileSystemObject")
strCommand = fso.BuildPath(strPath, strProgram)
...
intReturn = objProcess.Create(strCommand, strPath, objConfig, intProcessID)
Using the BuildPath method will save you the headaches caused by having to keep track of leading/trailing backslashes.
Note that you need to put double quotes around a path that contains spaces, e.g. like this:
strCommand = Chr(34) & fso.BuildPath(strPath, strProgram) & Chr(34)
As others have already pointed out, there are simpler ways to start a process on the local computer, like Run:
Set sh = CreateObject("WScript.Shell")
sh.Run strCommand, 1, True
or ShellExecute:
Set app = CreateObject("Shell.Application")
app.ShellExecute strCommand, , strPath, , 1
There are some notable differences between Run and ShellExecute, though. The former can be run either synchronously or asynchronously (which means the command either does or doesn't wait for the external program to terminate). The latter OTOH always runs asynchronously (i.e. the method returns immediately without waiting for the external program to terminate), but has the advantage that it can be used to launch programs with elevated privileges when UAC is enabled by specifying the verb "runas" as the 4th argument.
However, these methods only allow for launching processes on the local computer. If you want to be able to launch processes on remote computers you will have to use WMI:
strComputer = "otherhost"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
See here for more information about WMI connections to remote hosts.

Run script in background

I want to run following script as scheduled task on Windows 7 in background. Now, script displays cmd window and, can I run script without visible cmd window?
Option Explicit
Dim WshShell, oExec
Dim RegexParse
Dim hasError : hasError = 0
Set WshShell = WScript.CreateObject("WScript.Shell")
Set RegexParse = New RegExp
Set oExec = WshShell.Exec("%comspec% /c echo list volume | diskpart.exe")
RegexParse.Pattern = "\s\s(Volume\s\d)\s+([A-Z])\s+(.*)\s\s(NTFS|FAT)\s+(Mirror|RAID-5)\s+(\d+)\s+(..)\s\s([A-Za-z]*\s?[A-Za-z]*)(\s\s)*.*"
While Not oExec.StdOut.AtEndOfStream
Dim regexMatches
Dim Volume, Drive, Description, Redundancy, RaidStatus
Dim CurrentLine : CurrentLine = oExec.StdOut.ReadLine
Set regexMatches = RegexParse.Execute(CurrentLine)
If (regexMatches.Count > 0) Then
Dim match
Set match = regexMatches(0)
If match.SubMatches.Count >= 8 Then
Volume = match.SubMatches(0)
Drive = match.SubMatches(1)
Description = Trim(match.SubMatches(2))
Redundancy = match.SubMatches(4)
RaidStatus = Trim(match.SubMatches(7))
End If
If RaidStatus <> "Healthy" Then
hasError = 1
'WScript.StdOut.Write "WARNING "
MsgBox "Status of " & Redundancy & " " & Drive & ": (" & Description & ") is """ & RaidStatus & """", 16, "RAID error"
End If
End If
Wend
WScript.Quit(hasError)
Thanks a lot
Option 1 - If the task is running under your user credentials (if not, msgbox will not be visible)
There are two possible sources for the cmd window.
a) The script itself. If the task is executing cscript, the console window will be visible, avoid it calling wscript instead
b) The Shell.exec call. The only way to hide this window is to start the calling script hidden. On start of your script test for the presence of certain argument. If not present, make the script call itself with the argument, using Run method of the WshShell object, and indicating to run the script with hidden window. Second instance of the script will start with the special parameter, so it will run, but this time windows will be hidden.
Option 2 - Running the task under system credentials.
In this case, no window will be visible. All will be running in a separate session. BUT msgbox will not be seen. Change MsgBox call with a call to msg.exe and send a message to current console user.

For each loop syntax error

There is a problem with this Windows Installer package. A program run as part of the setup did not finish as expected. Contact your support personnel or package vendor
Hey I wrote this script delete shares of a computer but when I run my script it repeats the same wscript.echo statating the share being deleted. Why does my code never end when run How do I fix that.
My fumction:
'The function that is called to run the command Line that deletes a specific share from a pc
Function DeleteThisShare(Share)
Dim objShell
'Logging The deleted Approved Shares
objDeletedFile.WriteLine (Now & " - Removed share " & Trim(Share))
DeleteThisShare = "net share " & chr(34) & Share & chr(34) &" /DELETE"
Wscript.echo DeleteThisShare
Set objShell = CreateObject("Wscript.Shell")
objShell.Run DeleteThisShare
End Function
My loops:
'Compares The UnApproved Shares to the Current Shares
For Each objItem In colItems
Dim StrNonUnapprovedShares, Item
StrCurrentShares = objItem.name
if instr(AdminShares,lcase(objitem.name)) > 0 or mid(objitem.name,2,1) = "$" or left(lcase(objitem.name),10) = "pkgsvrhost" then
'Skipping known admin share
Else
For each Item in arrUnApprovedLines
If Lcase(Item) = Lcase(strCurrentShares) Then
StrNonUnapprovedShares = (StrNonUnapprovedShares & strCurrentShares & vbCrLf)
End If
Next
End If
Next
Dim notUnapprovedShares, notUnapprovedLines
notUnapprovedLines = StrNonUnapprovedShares
notUnapprovedLines = Split(notUnapprovedLines, vbCrLf)
Dim y, Line2
For y = 0 to uBound(notUnapprovedLines)
Line2 = Trim(notUnapprovedLines(y))
If len(Line2) > 0 Then
DeleteThisShare(Line2)
End If
Next
I think the problem is caused by using the function name as a variable. That's okay with VB that you're compiling, but I don't think VBScript recognizes it in the same way. Use a separate variable name in place of DeleteThisShare, e.g. strDeleteThisShare.
If I had to guess it's because you're creating a recursive loop by having your script echo the DeleteThisShare function. The function gets to that line and is called again before it's able to carry on.
Try to only assign values to the result of the function and use local variables to store any other debugging / temporary values.

Resources