Rectangle 27 19

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.

Nice use of //nologo and well remembered on the test of space (and then adding the quotes) for each argument.

The CreateObject line is missing a space between the script name and the arguments. As such, the run command fails. To fix, change WScript.ScriptFullName & """" & Str to WScript.ScriptFullName & """ " & Str.

FYI: I edited the script to include the space / add line breaks to display the code better on site. However I just realised the space isn't missing - during the for loop spaces are prefixed on all arguments. As well as separating arguments from one another, the first of these separates them from the script name.

vbscript - Force a VBS to run using cscript instead of wscript - Stack...

vbscript arguments wsh
Rectangle 27 2

The concatenation (&) is at the wrong palce:

Set objShell = CreateObject("Wscript.Shell") objShell.run("powershell.exe -noexit -file .\ps_v2.ps1") &Input

Set objShell = CreateObject("Wscript.Shell") objShell.run("powershell.exe -noexit -file .\ps_v2.ps1 " & Input)

vbscript - call Powershell in VBS with parameters - Stack Overflow

powershell vbscript arguments
Rectangle 27 6

You can try using the Wshshell.Run method which gives you little control of the process you start with it. Or you could use the WshShell.Exec method which will give you control to terminate it, get a response, pass more parameters (other than commandline args), get status, and others

Dim ProgramPath, WshShell, ProgramArgs, WaitOnReturn,intWindowStyle
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
intWindowStyle=1
WaitOnReturn=True
WshShell.Run Chr (34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs,intWindowStyle, WaitOnReturn

ProgramPath is the full path to your script you want to run ProgramArgs is the arguments you want to pass to the script. (NOTE: the arguments are separated by a space, if you want to use an argument that contains a space then you will have to enclose that argument in quotes [Safe way to do this is use CHR (34) Example ProgramArgs= chr (34) & "/Hello World" & chr (34)])IntWindowStyle is the integer that determines how the window will be displayed. More info on this and WaitOnReturn can be found here WshShell.Run MethodWaitOnReturn if true then the script will pause until the command has terminated, if false then the script will continue right after starting command.

ExitCode=WshShell.Run (Command,intWindowStyle,True)
Dim ProgramPath, WshShell, ProgramArgs, Process, ScriptEngine
Set WshShell=CreateObject ("WScript.Shell")
ProgramPath="c:\test run script.vbs"
ProgramArgs="/hello /world"
ScriptEngine="CScript.exe"
Set Process=WshShell.Exec (ScriptEngine & space (1) & Chr(34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs)
Do While Process.Status=0
    'Currently Waiting on the program to finish execution.
    WScript.Sleep 300
Loop

ProgramPath same as Run READ RUN'S DESCRIPTIONProgramArgs DITTO ScriptEngine The Engine you will be using for executing the script. since the exec method requires a win32 application, you need to specify this. Usually either "WScript.exe" or "CScript.exe"Process this is the Object that references to the program the script will start. It has several members and they are: ExitCode, ProcessID, Status, StdErr, StdIn, StdOut, Terminate.

  • ExitCode This is the exit code that is returned when the process terminates.
  • ProcessID This is the ID that is assigned to the process, every process has an unique processID.
  • Status This is a code number that indicates the status of the process, it get set to '-1' when the process terminates.
  • StdErr This is the object that represents the Standard Error Stream
  • StdIn This is the Object that represents the Standard Input Stream, use it to write additional parameters or anything you want to pass to the script you are running. (Process.StdIn.WriteLine "Hello Other Worlds")
  • StdOut This is the Object that represents the Standard Output Stream, It is READONLY so you can use Process.StdOut.ReadLine If there is nothing to read then the script will hang while waiting for an output. meaning the script will appear to be Not Responding
  • Terminate Call this method to force terminate the process.

Run a vbscript from another vbscript - Stack Overflow

vbscript
Rectangle 27 11

If that parameter requires quotes you could use a named parameter to identify it and then enclose the value with the double quotes

dim arg
if WScript.Arguments.Named.Exists("a") then
    arg = WScript.Arguments.Named("a")
    arg = chr(34) & arg & chr(34)
end if

and used thus:

cscript test.vbs /a:"a parameter"

but this doesn't help if you merely want to keep quotes if supplied. Single quotes are accepted though, so you could alternatively use single quotes (or another character/string) and do a Replace(arg, "'", chr(34)) to convert to double-quotes.

Double quotes in VBScript argument - Stack Overflow

vbscript
Rectangle 27 3

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.

vbscript - Force a VBS to run using cscript instead of wscript - Stack...

vbscript arguments wsh
Rectangle 27 3

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();

vbscript - Force a VBS to run using cscript instead of wscript - Stack...

vbscript arguments wsh
Rectangle 27 1

You can run a VBScript from a batch file like this (the parameter //NoLogo prevents the interpreter from printing the version/copyright banner all the time):

cscript //NoLogo C:\your.vbs 23

Use the Arguments property for receiving the argument (23) in the VBScript:

value = WScript.Arguments(0)

and pass a value back to the batch script via the return value:

WScript.Quit 42
value = WScript.Arguments(0)
WScript.Quit value + 19
@echo off

cscript //NoLogo C:\your.vbs %1
echo %errorlevel%
C:\>batch.cmd 23
42

C:\>batch.cmd 4
23

If you need to pass text back and forth, passing the response back to the batch script becomes more complicated. You'll need something like this:

for /f "tokens=*" %%r in ('cscript //NoLogo C:\your.vbs %1') do set "res=%%r"
str = WScript.Arguments(0)
WScript.StdOut.WriteLine str & " too"
@echo off

setlocal

for /f "tokens=*" %%r in ('cscript //NoLogo C:\your.vbs %1') do set "res=%%r"
echo %res%
C:\>batch.cmd "foo"
foo too

C:\>batch.cmd "and some"
and some too

On a more general note: why do you use batch/VBScript in the first place? PowerShell is far more versatile than both of them combined, and is available for any halfway recent Windows version.

vbscript - How to Pass a Variable Between Batch and VBS? - Stack Overf...

batch-file vbscript
Rectangle 27 2

Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.

::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &@echo off
rem^ &call :'sub
rem^ &exit /b

:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b

'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester

How to run VBScript from command line without Cscript/Wscript - Stack ...

vbscript
Rectangle 27 2

Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.

::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &@echo off
rem^ &call :'sub
rem^ &exit /b

:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b

'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester

How to run VBScript from command line without Cscript/Wscript - Stack ...

vbscript
Rectangle 27 1

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.

Sadly this won't work as I don't have control over the computer where this script will be run. I need to be able to give them mycode.vbs and know that however they try to run it, it will always be run with cscript rather than wscript.

vbscript - Force a VBS to run using cscript instead of wscript - Stack...

vbscript arguments wsh
Rectangle 27 2

What happens when you call a script without naming the interpreter/host, depends on the assoc/ftype file association settings.

assoc .vbs
.vbs=VBSFile

and

ftype VBSFile
VBSFile=%SystemRoot%\System32\CScript.exe "%1" %*

to make sure that the command line pattern contains the %* to forward the arguments.

assoc/ftype are command line tools. A simple assoc /? resp. ftype /? will show you the details (including a sample that deals with parameters). But use the method you are familiar with.

Ah cool, I did not know you had to do that. Are you running those commands via the command line? - and if so , does that change it globally? (i made vbs association via the windows GUI interface)

You should be changing it via the correct tools. Type wscript /? (or cscript /?) to see how to change.

@Noodles - the problem is not to change the default host, but to handle/pass on the arguments.

He changed it manually, so incorrectly. Fix it by doing it correctly.

@Noodles I changed the association for .vbs via Control Panel\Programs\Default Programs\Set Associations. I changed it back now to windows based script instead of console based. But infact I still get the same issue. ftype VBSFile yields: VBSFile="%SystemRoot%\System32\WScript.exe" "%1" %*. So I am just calling my script with through cscript....

vbscript - Running vb script does not "see" parameters unless I run wi...

vbscript parameters
Rectangle 27 3

Your question is unclear, but I think the START command may be what you're looking for. This allows a process to be started from a batch file, but the batch file will continue executing more commands, instead of waiting for that command to finish.

vbscript - How Can I run a bat file simultaneously with the vbs script...

batch-file vbscript cmd command-prompt
Rectangle 27 9

you can keep your original script, only need to give a parameter to indicate local setting must apply. This saves my CSV with a ; separator

if WScript.Arguments.Count < 2 Then 
  WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv" 
  Wscript.Quit 
End If 
Dim oExcel 
Set oExcel = CreateObject("Excel.Application") 
oExcel.DisplayAlerts = FALSE 'to avoid prompts
Dim oBook, local
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
local = true 
call oBook.SaveAs(WScript.Arguments.Item(1), 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, local) 'this changed
oBook.Close False 
oExcel.Quit 
WScript.Echo "Done"

Converting xls to csv using VBScript and separate by semicolons - Stac...

csv vbscript xls xlsx
Rectangle 27 1

It looks like it may be dependent on the parameters, but it seems that it is possible for the script to attempt to write to the objLogProgram after it has been closed

If comparison = 0 Then
    objLogProgram.WriteLine datestamp2&vbTab&Wscript.ScriptName&vbTab&"INFO"&vbTab&"UPDATE STOPPED. AVP FILE IN LOCAL IS UPDATED."
    objLogProgram.Close

and later

If tokenGenHash = True Then
    objLogProgram.WriteLine datestamp2&vbTab&Wscript.ScriptName&vbTab&"SUCCESS"&vbTab&"AVP SUCCESSFULLY DOWNLOADED. GENERATING HASH FOR VALIDITY"
    objLogProgram.Close
    ' ...
Else
    objLogProgram.WriteLine datestamp2&vbTab&Wscript.ScriptName&vbTab&"ERROR"&vbTab&"AVP WAS NOT TRANSFERRED PROPERLY."
    objLogProgram.Close
    ' ...

vbscript runtime error object variable not set when using object.write...

vbscript
Rectangle 27 2

Paths with spaces are typically enclosed in quote characters ("). In VBScript, to insert a quote character into a string you use double quotes (""). So, your code should look like this:

oShell.Run "cmd /c Client\setupclient.exe /q /targetdir ""c:\program files\Microsoft CRM""", 1, true

Also, I'm not sure if cmd /c is actually needed here, so it might work this way as well:

oShell.Run "Client\setupclient.exe /q /targetdir ""c:\program files\Microsoft CRM""", 1, true

vbscript - vbs cmd path space - Stack Overflow

vbscript path cmd space
Rectangle 27 54

Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.

Just to add the third bool parameter represents if the call is to be made async or sync. False value means it will be a synchronous call. Also the open API has two more parameter for authentication to pass Userid and password if it is required by the website being called.

I'm having problems using this method from Windows 2012, I think that's due to the lot of different versions released by microsoft. I am thinking of using antoher method for make an HTTP Get from vbs, any ideas??

Simple example for a simple question. It took me 2 hours to find this, which is all I needed. Bravo!

vbscript - HTTP GET in VBS - Stack Overflow

http vbscript request
Rectangle 27 34

You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of MSXML2.XMLHTTP (I recommend the more explicit MSXML2.XMLHTTP.3.0 progID) however you may need to do different things with the response, it may not be text.

The XMLHTTP also has a responseBody property which is a byte array version of the reponse and there is a responseStream which is an IStream wrapper for the response.

Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use MSXML.ServerXMLHTTP.3.0 or WinHttp.WinHttpRequest.5.1 (which has a near identical interface).

Here is an example of using XmlHttp to fetch a PDF file and store it:-

Dim oXMLHTTP
Dim oStream

Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")

oXMLHTTP.Open "GET", "http://someserver/folder/file.pdf", False
oXMLHTTP.Send

If oXMLHTTP.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write oXMLHTTP.responseBody
    oStream.SaveToFile "c:\somefolder\file.pdf"
    oStream.Close
End If

hey anthony! How would we specify auth keys or request arguments externally? or we can just keep that a part of the url.

@SushantKhurana: The would depend on what the server is expecting. You an include additional headers in the request with addHeader method so if you have control of both ends you create some custom "x-myheader" header. Or you can use a "POST", add a Content-Type header like "application/x-www-form-urlencoded" and pass a urlencoded string contianing parameter to the send method. Or as you say include the values in the query string. It really depends on what you have available to you on the server.

Yes. I have to do that via a Basic HTTP Authorization header only. Example Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

@SushantKhurana@ For basic authorization just specify the username and password as the 4th and 5th parameters in the XMLHttp open method call.

vbscript - HTTP GET in VBS - Stack Overflow

http vbscript request
Rectangle 27 1

if you want to create the vbs file in the bat you can use this

echo do > test.txt
echo msgbox"hi" >> test.txt
echo loop >> test.txt
ren test.txt test.vbs
start test.vbs
pause 
del test .vbs

this creates an infinite loop of text windows, but you can put whatever in there, it wont have the "wscript.echo" in the .vbs

vbscript - How Can I run a bat file simultaneously with the vbs script...

batch-file vbscript cmd command-prompt
Rectangle 27 1

don't map, do the comparison directly with the url

on error resume next
path = "\\192.168.1.103\SCRIPT\SCRIPTTEXT.txt"
if objFSO.fileExist(path)
  Set objServerFile = objFSO.GetFile(path)
  dtmServerDate = objServerFile.DateLastModified
  if dtmLocalDate < dtmServerDate Then
    objFSO.CopyFile objServerFile.Path, objLocalFile.Path, OverwriteExisting
  end if
else
  objFSO.CopyFile objServerFile.Path, objLocalFile.Path
end if

Thanks for this how can I loop it through FileA.txt, FileB.txt FileD.txt, FileE.txt, FileF.dll, FileG.dll the .dll s' are not in the same folder

see another answer of me which deletes empty files in a folder, use the same technique stackoverflow.com/questions/10450639/

vbscript - VBS check a list of files - Stack Overflow

vbscript
Rectangle 27 6

You will either have to put it in the Startup folder or run it from the registry.

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

the question is how to run vbs script on startup not from where

@K3rnel31 So, you basically copy my answer and then downvote me? The OP did not ask how to launch a script in general, but rather at startup and without putting a shortcut in the startup folder. I answered with the other possible options.

vbscript - launch VBS script after PC startup - Stack Overflow

vbscript