Append or put variable within string in vbscript? - string

I am wanting to include the variable domainUser within the quoted command sent to the commandline but I am not having any luck. What I am trying to accomplish is to create a log file titled with their domain name but I keep getting errors or just getting a txt file with no title.
Dim domainUser
domainUser = Example123
objInParam.Properties_.Item("CommandLine") = "cmd /c ECHO Test >> c:\UserLogs\"""domainUser""".txt"
So line 4 would be read like this (or whatever domain user I put in on line 2)...
objInParam.Properties_.Item("CommandLine") = "cmd /c ECHO Test >> c:\UserLogs\Example123.txt"

You need concatenation to splice a variable's content into a string and double double quotes to put double quotes into it:
>> Dim domainUser
>> domainUser = "Example123"
>> Dim cmd
>> cmd = "cmd /c ECHO Test >> ""c:\UserLogs\" & domainUser & ".txt"""
>> WScript.Echo cmd
>>
cmd /c ECHO Test >> "c:\UserLogs\Example123.txt"

Related

Build a TXT file with text and variables and send variables via CURL using Bash shell script

I am trying to build a .txt file with variable entries on multiple lines along with some static text and then send some of the variable data via CURL in a POST request.
ISSUES
At the moment, the .txt file is built but they are all added to a single line rather than multiple lines.
Only one variable (image1ID) is being sent via CURL, the other variable is being omitted from the payload.
IDEAL OUTCOME
TXT file to contain
file https://www.amazon.com/1.jpg
11
file https://www.amazon.com/2.jpg
13
...
and send all images variables via CURL
#!/bin/bash
image1Url=https://www.amazon.com/1.jpg
image1IDNumber=11
image2Url=https://www.amazon.com/2.jpg
image2IDNumber=13
image3Url=https://www.amazon.com/3.jpg
image3IDNumber=15
image4Url=https://www.amazon.com/4.jpg
image4IDNumber=17
image5Url=https://www.amazon.com/5.jpg
image5IDNumber=19
# Build txt using variables
echo "'file '${image1Url}\n${image1IDNumber}\n'file '${image2Url}\n${image2IDNumber}\n'file '${image3Url}\n${image3IDNumber}\n'file '${image4Url}\n${image4IDNumber}\n'file '${image5Url}\n${image5IDNumber}\n" >imagedetails.txt
curl -H "content-Type: application/json" -d {"image1ID":"${image1IDNumber}","image2ID":"${image2IDNumber}"} https://requestbin.herokuapp.com/18y57z13
I think i undestand what you're trying to do there.
Im' wondern why you complicated things ? As it seems, your variables are 5, if they are dynamic you should've use a loop instead.
The following code gives your Ideal Outcome . The easiest way to do it :
#!/bin/bash
image1Url=https://www.amazon.com/1.jpg
image1IDNumber=11
image2Url=https://www.amazon.com/2.jpg
image2IDNumber=13
image3Url=https://www.amazon.com/3.jpg
image3IDNumber=15
image4Url=https://www.amazon.com/4.jpg
image4IDNumber=17
image5Url=https://www.amazon.com/5.jpg
image5IDNumber=19
# Build txt using variables
echo " file $image1Url " >> imagedetails.txt
echo " $image1IDNumber " >> imagedetails.txt
echo " file $image2Url " >> imagedetails.txt
echo " $image2IDNumber " >> imagedetails.txt
echo " file $image3Url " >> imagedetails.txt
echo " $image3IDNumber " >> imagedetails.txt
echo " file $image4Url " >> imagedetails.txt
echo " $image4IDNumber " >> imagedetails.txt
echo " file $image5Url " >> imagedetails.txt
echo " $image5IDNumber " >> imagedetails.txt
### Post the content of the file as follow :
a="\"image1ID\":\"${image1IDNumber}\",\"image2ID\":\"${image2IDNumber}\""
b="'$a'"
curl -H "content-Type: application/json" -d $b https://requestbin.herokuapp.com/18y57z13
you should file an imagedetails.txt file containing the following output :
file https://www.amazon.com/1.jpg
11
file https://www.amazon.com/2.jpg
13
file https://www.amazon.com/3.jpg
15
file https://www.amazon.com/4.jpg
17
file https://www.amazon.com/5.jpg
19

Get an echo batch-file answer with VBA

In my VBA code I call the bat using Call Shell(....).
I need now to get the "Echo answer" inside the batch-file in VBA.
How can I do that?
My batch-file:
#echo off
IF exist %3 (robocopy %1 %2 /e ) ELSE (echo 1)
I want to get that "1" in VBA.
You can't return answers using Call Shell. You need to use WScript.Shell, and can use the read lines from the execution object it returns.
Dim sh As Object
Set sh = CreateObject("WScript.Shell")
Dim ex As Object
Set ex = sh.Exec("C:\Path\To\File.bat")
Dim ans As String
ans = ex.StdOut.ReadAll
A shorthand, if you want to save lines:
Dim ans As String
ans = CreateObject("WScript.Shell").Exec("C:\Path\To\File.bat").StdOut.ReadAll

error when passing string argument from batch to vbs

I'm calling a vbs string with a batch file. I'm passing a string through batch to vbs.
Complete batch file:
C:
cd C:\folder
Set arg = "sample foo"
Wscript titi.vbs "%arg"
pause
But, when I read the argument into the VBScript with str = Wscript.Arguments(0) the value of str is sample and not to sample foo
How can I fix it?
The problem is a simple one and one which is commonly made by those having used other programming languages.
Set arg = "sample foo"
sets the variable: %argspace% to the string: space"sample foo"
The way to assign variables should be:
Set arg="sample foo"
or:
Set "arg="sample foo""
I prefer the latter.
BTW, you also missed a closing % when using "%arg" instead of "%arg%".
Because you are using the argument as "%arg%" there is no neeed to set the double quotes into the actual variable string.
Just use:
CD /D "C:\folder"
Set "arg=sample foo"
Wscript titi.vbs "%arg%"
Pause
I tried below and working as expected,
1.vbs
str = Wscript.Arguments(0)
WScript.Echo(str)
1.bat
Wscript 1.vbs "sample foo"
cmd line output
The batch file you posted should have the VBScript output arg due to your malformed variable syntax. Even if you corrected %arg to %arg% you should get an empty string as output, because your variable assignment is malformed as well (set arg =... defines a variable %arg %).
Change
Set arg = "sample foo"
Wscript titi.vbs "%arg"
to
set "arg=sample foo"
Wscript titi.vbs "%arg%"
and the problem will disappear.

How to enter multiple line of code in CMD from VBA?

I want to open a cmd.exe and then execute a few lines of code.
I searched the web for some examples.
Code I tried modifying:
strToPrint = "Hello World!"
Shell "cmd.exe /K echo " & strToPrint, vbNormalFocus
I found How to write message to command window from VBA?
I tried multiple lines of coding, but the lines are executed in different command windows:
Sub CMD_VBA_Script()
Shell "cmd.exe /K echo Hello World!", vbNormalFocus
Shell "cmd.exe /K color 0a", vbNormalFocus
End Sub
I understand when I call the Shell two times, that it will execute two times.
My goal is to call the following script from VBA:
#echo off
title Matrix
color 0a
mode 1000
:a
echo %random%%random%
goto a
How can I execute multiple lines of code from VBA in command prompt?
MyFile = "C:\cmdcode.bat"
fnum = FreeFile()
Open MyFile For Output As #fnum
Print #fnum, "#echo off"
Print #fnum, "title Matrix"
Print #fnum, "color 0a"
Print #fnum, "mode 1000"
Print #fnum, ""
Print #fnum, ":a"
Print #fnum, "echo %random%%random%"
Print #fnum, "goto a"
Close #fnum
' Run bat-file:
Shell MyFile, vbNormalFocus
' optional, remove bat-file:
Kill "C:\cmdcode.bat"
So in short. You need to create a bat-file that you run.
If you don't need the bat-file after it's done you can delete it with Kill
You can write something like this -
Call Shell("cmd.exe /c "cd C:\Users\username\local\temp\" & " && temp.vbs" & " && mkdir newfolder")
This executes 3 lines of command:
Change directory
Execute a vbs file
Make a new folder
It looks like you want to execute a Command Prompt Batch file - batches are stateful, so simply executing each line separately is not going to have the same effect as executing the batch as a whole.
Two other alternative approaches involve faking batch execution by instructing an interactive instance of cmd.exe to execute commands as-they're-entered by some automated process: either sending window messages, or piping into the cmd process' stdin stream. I do not recommend either of these approaches because of their inherent flakiness (i.e. dependency on undocumented behavior)
So the best approach would be to just execute a batch file as it's intended - you would need to write the batch to a temporary file first, and then execute it:
Using the code from here: https://support.microsoft.com/en-us/kb/195763
Dim tempFileName As String
tempFileName = CreateTempFile("SomeBatch.cmd")
WriteToBatchFile( tempFileName ) ' you will have to write to the temp batch file yourself here
Shell "cmd.exe /c """ & tempFileName & """", vbHide, True ' Run the batch file, then cmd.exe will terminate. The Shell function will block until cmd is closed
Kill tempFile ' delete the temp batch file
Use "cmd.exe /K" option, and '&' to connect multiple commands.
In C:\Users\%USERNAME%, create test.bat with two simple commands:
echo %PATH%
dir
Here is the complete sample:
Sub Demo_Multi_Commands()
Cmd1 = "cd " & Environ("USERPROFILE")
Cmd2 = "test.bat"
Connector = " & "
Commands = "cmd.exe /K " & Cmd1 & Connector & Cmd2 & Connector & "systeminfo"
Debug.Print Commands
pid = Shell(Commands, vbNormalFocus)
End Sub
Environment: Windows 10 Enterprise, VBA 7.1

How do I pass multiple variables from an Excel file to a batch file

I am currently able to pass one argument from my Excel file to my batch file using the following:
filepath = "C:\Users\agaron\Desktop\batchmaster\batchfiles\batchfiletest.bat " & month
followed by calling a shell command:
Call Shell(filepath, vbNormalFocus)
This works fine. However, I now require to pass not just one, but 18 parameters using the above method. I tried concatenating using the & but it appears that the batch file recognizes all the parameters as a single one.
How can I pass more parameters from Excel to batch file?
Windows batch files get different parameters delimited by spaces. So if your batch file batchfiletest.bat is like:
echo off
echo %1
echo %2
echo %3
pause
then the following VBA should run properly:
Sub testBatch()
sMonth = Format(Now, "mmmm")
sDay = Format(Now, "dd")
sYear = Format(Now, "yyyy")
filepath = "C:\Users\axel\batchfiletest.bat " & sMonth & " " & sDay & " " & sYear
Shell filepath, vbNormalFocus
End Sub
To provide multiple parameters to a batch file, separate them with spaces. If a parameter contains spaces on its own, enclose it in "" (this is also required for some other characters like ,, ;, =; use quotes also for the batch file path in case; the quotes might also be used for every parameter):
"C:\Users\agaron\Desktop\batchmaster\batchfiles\batchfiletest.bat" param1 param2 "param3 with spaces" ...
To access the parameters in the batch file, use the %# syntax, were # represents a single decimal digit (see call /? for details). Note that %0 returns the path of the batch file itself. To remove potential surrounding "", use %~#:
echo This batch file: %~0
echo First parameter: %~1
echo Second parameter: %~2
echo Third parameter: %~3
With the shift command, you shift the assignment of the %# numbers, for instance:
echo This batch file: %~0
shift
echo First parameter: %~0
echo Second parameter: %~1
shift
echo Third parameter: %~1
As you might have noticed, you cannot access the batch file path anymore after the first shift; the next shifts prevents the first parameter from being accessed, and so on (type shift /? for more information).
However, shift lets you access more than 9 parameters. For example, when calling the batch file with a command line like:
"C:\Users\agaron\Desktop\batchmaster\batchfiles\batchfiletest.bat" param1 param2 param3 ... param9 param10
you can access the parameters like:
echo This batch file: %~0
echo Parameter 1: %~1
shift
echo Parameter 2: %~1
shift
echo Parameter 3: %~1
:: ...
shift
echo Parameter 9: %~1
shift
echo Parameter 10: %~1
As you can see, shift provides the possibility to access even more then 9 parameters.
Finally, let us call the batch file via the VBA code:
filepath = Chr(&H22) & "C:\Users\agaron\Desktop\batchmaster\batchfiles\batchfiletest.bat" & Chr(&H22) _
& " " & variable_containing_param1 _
& " " & "param2" _
& " " & Chr(&H22) & "param3 with spaces" & Chr(&H22)
Call Shell(filepath, vbNormalFocus)

Resources