Execute vbs command from cmd without a saved vbs file - node.js

How can one run a vbs command from cmd when the command is not saved?
For example to run a powershell command which has not been saved one can simply use powershell "get-childitem", where get-childitem is the command we want to use. We do not need to save a powershell file to run the command.
Let's say we want to run the vbs command Wscript.Echo Date() without saving a vbs file first, how can we do that?
I'm not looking to do this from a .bat file. I really am looking to embed a vbs script in a node.js script. I realize that this is not heavily reflected in the questions title :-/ I want to use exec and embed the vbs. It's important that there's no files other than the one js.
If I could run the vbs command from the cmd console without the use of any files then I could run the command from node.js without the need for any other files.
I don't think Is it possible to embed and execute VBScript within a batch file without using a temporary file? answers this as it's concerning using a batch file.
After the comments it looks like the way to go is using mshta
What I am trying to do is to access the Windows index from a Node js script.
Node Js allows me to exec cmd line commands.
So I can directly execute this command
powershell "$connector = new-object system.data.oledb.oledbdataadapter -argument \"SELECT System.ItemPathDisplay FROM SYSTEMINDEX WHERE CONTAINS (System.FileName, '\"\"Google Chrome\"\" OR Cefclient.exe')\", \"provider=search.collatordso;extended properties='application=windows';\"; $dataset = new-object system.data.dataset; if ($connector.fill($dataset)) { $dataset.tables[0] }" which will return the result from the Windows index. The problem with this method is that it takes about 10 seconds just to get powershell running.
To do the same thing in vbs one can use
Set objConnection=CreateObject("ADODB.Connection")
Set objRecordSet=CreateObject("ADODB.Recordset")
objConnection.Open "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';"
objRecordSet.Open "SELECT System.ItemPathDisplay FROM SYSTEMINDEX WHERE CONTAINS (System.FileName,'Chrome OR Cefclient.exe')",objConnection
objRecordSet.MoveFirst
Do Until objRecordset.EOF
Wscript.Echo objRecordset.Fields.Item("System.ItemPathDisplay")
objRecordset.MoveNext
Loop
This is much quicker. However the only way for me to run the vbs with nodejs seems to be by converting the code to a format that mshta accepts.
I am now trying to convert this to a valid mshta format. To do so I am using this snippet.
var vbs, before, after;
vbs = `Set objConnection=CreateObject("ADODB.Connection")
Set objRecordSet=CreateObject("ADODB.Recordset")
objConnection.Open "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';"
objRecordSet.Open "SELECT System.ItemPathDisplay FROM SYSTEMINDEX WHERE CONTAINS (System.FileName,'Chrome OR Cefclient.exe')",objConnection
objRecordSet.MoveFirst
Do Until objRecordset.EOF
Wscript.Echo objRecordset.Fields.Item("System.ItemPathDisplay")
objRecordset.MoveNext
Loop`;
before = 'mshta "vbscript:window.close(execute("';
after = '"))"';
vbs = vbs.replace(/\n/g,':').
replace(/"/g, '""').
replace(/ /g, '"&chr(32)&"');
vbs = before + vbs + after;
$('#vbs').text(vbs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code id="vbs"></code>
I can see that the conversion method is not fail-proof but can't see where it's going wrong in this case.
If anyone can get the above mshta to work it would be much appreciated.

Sorry to revive this old post, but I've found a way to do this in pure Batch. It uses 'mshta.exe', a utility that is installed on most Windows versions by default. Here is an example:
mshta vbscript:Close(MsgBox("Hello, World!"))
This method does not write to disk. Further reading on 'mshta.exe' can be found here.
Hope this helps.
-Gabe

Related

VBA print console output when running script with exec

I wish I could run a vba script (which calls a python script) without using WaitOnReturn (so it keeps my Excel unblocked) and displaying stdout in real time in a console.
I run the script from Excel 365 on a Windows machine.
I know I can launch script using Run or Exec. As I didn't want to block Excel, I use here Exec.
But I don't manage to display outputs from the script in the console Excel opens.
Any help please ?
Here's my code :
Set wsh = VBA.CreateObject("WScript.Shell")
Dim obj_exec: Set obj_exec = wsh.exec("foo")
While obj_exec.Status = 0
Debug.Print obj_exec.StdOut.ReadLine()
Wend
I was hoping Debug.Print would work ...

How is AppleScriptTask called from Excel 365 VBA on Mac mini running Big Sur?

I am trying to run an AppleScript from VBA in an Excel 365 macro and I keep getting:
Run-time error '5': Invalid procedure call or argument
I have this script called "PythonCommand.scpt" in my /Library/Application Scripts/com.microsoft.Excel folder:
on PythonCommandHandler(pythonScript)
--do shell script "/usr/local/bin/Python3" & pythonScript
return "Handler ended! " & pythonScript
end PythonCommandHandler
I commented out the "do" statement so I should simply get back what I send it. I tested this in the script editor by adding a line to invoke the function and it works just fine.
I have this code in my VBA macro:
Dim result As String
Dim strPyScript As String
strPyScript = "xxxx"
result = AppleScriptTask("/Library/Application Scripts/com.microsoft.Excel/PythonCommand.scpt", "PythonCommandHandler", strPyScript)
and when I run it I get the error '5'.
I tried changing the first argument to just "PythonCommand.scpt" instead of the whole path but got the same error. I tried putting the last argument in as a quoted string instead of using a variable and got the same result. I have looked at this post:
How can I launch an external python process from Excel 365 VBA on OSX?
and started my coding from there (this example had the first argument with no path). Then I read this one:
https://learn.microsoft.com/en-us/office/vba/office-mac/applescripttask from Microsoft which is specific to using the AppleScriptTask command. It lays out the process a bit more clearly but is basically the same. I also looked at this post:
How to simply run an applescript task from mac excel 2016
which has a broken link to a Ron deBruin article which I found here:
https://macexcel.com/examples/setupinfo/applescripttask/index.html
Which is quite clear and easier to read but says basically the same thing. The post with the broken link was resolved by making the script an app and invoking it as a hyperlink. I tried that and it works but there are several shortcomings with that approach: can't pass an argument to the script, can't get anything back from the script, and control does not wait for the script to end before executing the next line of VBA code. I really want to make the AppleScriptTask command work. I feel I must be missing something. If others have gotten this to work I must be doing something wrong. I tried turning on all the references I could find in Tools References but that didn't change anything, I still got the error '5': message. Please help me out here if you can. I really appreciate any help you can offer.
Thanks
Phil
Phil,
The code I use is:
res = AppleScriptTask("selectFile.scpt", "GetFile", args)
NB I don't need to put the full path to the scpt file. I presume this is because it is sandboxed and so vba knows where it is.
BTW I put the scpt file in this folder:
${HOME}/Library/Containers/com.microsoft.Excel/Data/Library/Application Scripts/com.microsoft.Excel
The folder you have specified is not a user folder, but rather a system folder.

Executing VB script from Spring Boot Application

I want to execute a VB script from Spring Boot application, the script is like:
' Creating a file as test acces to macro
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CreateTextFile("C:\excel\FLAG_TEST")
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\excel\excelFile.xls")
objExcel.Application.EnableEvents = False
objExcel.Application.DisplayAlerts = False
objExcel.Application.Run "excelFile.xls!executeMacroFunction"
objExcel.Application.Quit
I tried to execute the script from Spring Boot service by:
Runtime.getRuntime().exec(new String[]{"C:\\Windows\\System32\\wscript.exe", "C:/vb/script.vbs"});
The above line code does not work on the application deployed on Tomcat 9 (it works fine when running as Spring Boot App on Eclipse)
Then I tried to execute the script via a batch file launched from the app
On batch file, I tried to execute the VB script by
rem First way
Set wscript = CreateObject("WScript.Shell")
wscript.Run "C:/vb/script.vbs"
--------------------
rem Second way (System 64bit)
C:\Windows\System32\wscript.exe C:/vb/script.vbs
--------------------
rem Third way (System 64bit)
wscript C:/vb/script.vbs
And running the batch file from Java with different ways too:
// First way
ProcessBuilder processBuilder = new ProcessBuilder("C:/batch/executor.bat");
final Process process = processBuilder.start();
// Second way
Process process = Runtime.getRuntime().exec("cmd /c start \"\" C:/batch/executor.bat");
// Third way
Process process = Runtime.getRuntime().exec(
"cmd /c start \"\" C:/batch/executor.bat",
null,
new File("C:\\Windows\\SysWOW64"));
All these ways do not work, the scripts have no problem since they work when I run manually the batch file (by double click)
On the execution of the macro from Spring Boot, the test file (FLAG_TEST) is created and then the execution is blocked at the line:
Set objExcel = CreateObject("Excel.Application")
Am I missing something ?...Thanks a lot in advance !
Tried also with Jacob DLL to run the Macro inside the excel file, it also didn't work for me within a Tomcat server
I decided at the end to abandon any kind of external tool and do the thing within Spring Boot, parsing the Excel file via an Excel Java API and migrating the Macro program to Java: JExcel
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
Unlike some other Excel parsing APIs, the Jexcel get the cell text as it is: String, Number, Boolean, Formula (its displayed result), no need to handle the different cases of content type
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.WorkbookSettings;
// Set Encoding 1252 that supports many European languages (special characters included)
WorkbookSettings workbookSettings = new WorkbookSettings();
workbookSettings.setEncoding("Cp1252");
Workbook workbook = Workbook.getWorkbook(new File(EXCEL_FILE_LOCATION), workbookSettings);
Sheet sheet = workbook.getSheet(0);
Cell cellDemo = sheet.getCell(0, 0); // Or sheet.getCell("A1");
// Get the displayed cell centent as a text
String cellContent = cellDemo.getContents();
System.out.print("Cell A1 centent:" + cellContent);
The Java parsing makes the exception handling of data validation easier and more precise, no kind of abstract HMI error message (Error occurred wile processing the Excel file...)
Turns out that the Excel Java reading API implementation took less time than the several attempts of runing the Macro externally :D

Importing Excel files into Access with Excel 2016

We currently have Office 2010 and are moving to Office 2016. I have an Excel macro that I am try to testing. I use the following shell command to open access and run a macro to import some excel files into a database. This has worked great and never has any issues.
Shell "C:\PROGRA~1\MICROS~1\Office14\MSACCESS.EXE \\Vs300\rental_public\SHARED~1\SSDATA~2.MDB /X Upload_Manheim", vbMaximizedFocus
When I look for the Access application on my machine the path is as follows:
C:Program Files\Microsoft Office\Office14
When I search for the Access application on the test machine, the path is as follows:
C:Program Files (x86)\Microsoft Office\root\Office16
I've tried modifying the shell command as follows:
Shell "C:\PROGRA~1\MICROS~1\root\Office16\MSACCESS.EXE \\Vs300\rental_public\OFFICE~1\SHARED~1\SSDATA~1.MDB /X Upload_Manheim", vbMaximizedFocus
When I try to run my macro, I'm getting a file not found error message. I believe the 2nd half of the shell command is fine, so I believe it is the issue is in the 1st half of the shell command.
The database being opened is an Access 2000 database. I'm not sure what is wrong.
Instead of going thru the command line you could stay inside your Excel Macro and do the same without making reference to the location of the Access application. Instead you can create a new instance of MS Access from within vba, open the Access database the contains the macro, and then run the macro.
Something like:
Dim accApp As Access.Application
Dim db As Object
Set accApp = CreateObject("Access.Application")
accApp.OpenCurrentDatabase "Your database location\dbName", True
Set db = accApp.CurrentDb
With db
DoCmd.RunMacro "MacroNameHere"
End With
Set accApp = Nothing
Set db = Nothing
Good luck!

powershell script calling another script reading excel fails

only new to PowerShell so I hope someone can help me with my little issue.
I've written a script that accepts 2 parameters and opens and reads an excel file (lets call it excelRead.ps1). When I execute this by itself everything works fine.
However, when I call excelRead.ps1 from inside another script the code to open the excel file appears to fail with absolutely no error.
e.g.
. c:\runIt.ps1 -ws "valid - 20140528" -out "$out_file"
Anyone have any ideas as to why this might be happening?
Personally one of the three things I load in my sessions anytime I launch powershell is a script that loads 1 function: Import-Xls (by Francis de la Cerna). (Get it here!) Which really brings me to my point, (which I think was a Hey, Scripting Guy! blog a long time ago): Don't write scripts, write functions.
This would probably be simpler if you wrote your 'other script' as a function that could be called upon, and then run in the context of the current scope. For example, if you had the Import-Xls.ps1 file in the current path you could do something like:
. .\Import-Xls.ps1
$Data = Import-Xls <path to .XLS(x) file> -Worksheet "valid - 20140528"
Then you have the data from that sheet stored in $Data to do with as you please.

Resources