Running vbscript in windows

Объект WScript.Shell метод Run — запуск внешних программ

Доброго времени суток всем читателям блога scriptcoding.ru. В этой статье мы подробно рассмотрим метод Run Wscript.Shell объекта. Данный метод служит для запуска внешних приложений из тела сценариев Windows Script Host.

Для начала мы рассмотрим теоретическую часть, а потом приступим к программированию.

Run (strCommand, [intWindowStyle], [bWaitOnReturn]) – данный метод служит для запуска другого приложения как в консольном режиме (командная строка), так и в оконном. При открытии исполняемого файла создается новый процесс. Ему передаются следующие параметры:

strCommand – данный параметр является обязательным, поскольку задает путь для файла или команды. Стоит учитывать, что если путь содержит пробелы, то его обязательно стоит заключать в двойные кавычки, иначе, возникнет ошибка » The system cannot find the file specified » – система не может найти указанный файл. Также полезно, использовать переменные окружения в пути к приложению, это экономит время.

intWindowStyle – является необязательным, и задает стиль окна. Параметр может принимать целые значения от 0 до 10. Согласно документации, в языке vbscript можно использовать именованные константы, но, они не всегда дают ожидаемый результат, и так как эти значения между собой повторяются, я упомянул лишь три:

  • 0 – скрывает окно, будет виден только процесс в диспетчере задач.
  • 1 – нормальный режим
  • 2 – свернутый вид
  • 3 – развернутый вид

bWaitOnReturn – может принимать true – сценарий будет ожидать завершения работы запущенного приложения, и только потом перейдет к выполнению следующей строчки кода, false – будет продолжатся выполнение сценария независимо от того, завершилась работа запущенного приложения или нет. Также следует учесть, что если установлено true, то метод вернет код выхода вызванного приложения, если установлено false – всегда будет возвращаться ноль.

Хорошо, теперь настало время заняться программирование. Для начала напишем программный код на языке VBScript:

Давайте проанализируем логику работы данного сценария. Переменная path хранит путь к папке System32, так как в ней у нас лежат исполняемые файлы notepad и calc. Переменная окружения » %WINDIR% » позволяет сократить строки кода и не писать » C:\\Windows «. WshShell содержит ссылку на экземпляр объекта Wscript.Shell, видим, чтобы создать саму ссылку, мы перед переменной прописали ключевое слово set, после чего идет вызов метода CreateObject класса WScript, подробней о работе с объектами читайте «Урок 8 по VBScript: Объекты и классы» и «Урок 4 по JScript: Создание собственных объектов». Далее мы запускаем блокнот с помощью метода Run Wscript Shell класса, через переменную WshShell. Для программы notepad мы третий параметр команды Run поставили в true, поэтому, исполняемый файл calc запустится только после закрытия приложения блокнот, плюс, перед этим появится информационное сообщение.

Читайте также:  Почему windows просит пароль

Хорошо, теперь давайте посмотрим на аналогичный пример, но написанный уже на языке jscript.

В данном примере, мы видим, что для команды Run мы прописали второй параметр (1 – нормальный режим), если этого не сделать, то произойдет ошибка, язык jscript не дает нам возможности пропустить параметр. Также видим, что тут не нужно использовать дополнительное ключевое слово типа set.

WScript Shell Run

Хорошо, теперь давайте посмотрим на еще один пример на языке vbscript.

В этом примере мы также запустили приложение notepad, но, не прописывали путь к нему. Дело в том, что команда Run объекта Wscript.Shell работает как команда » Windows Пуск/Выполнить «, и при запуске приложения, сперва идет его поиск в переменных средах Windows, в которые, и входит папка System32 . Также видим, что мы передали программе содержимое нашего сценария (строка WScript.ScriptFullName), фактически, скопировали в него весть текст скрипта.

Ну и напоследок, аналогичный пример, но уже на языке jscript:

И так, давайте все подытожим… В этой статье мы разобрали метод Run класса Wscript Shell, который позволяет запускать заданное приложение, и передавать ему нужные параметры, так, мы можем открыть текстовый редактор и вставить в него нужный текст. Аналогично, можно использовать и метод Exec, который тоже позволяет запускать исполняемый файл, но в отличии от метода Run, он позволяет контролировать работу исполняемого файла.

Спасибо за внимание. Автор блога Владимир Баталий

Arguments

String value indicating the command line you want to run. You must include any parameters you want to pass to the executable file.

Optional. Integer value indicating the appearance of the program’s window. Note that not all programs make use of this information.

Optional. Boolean value indicating whether the script should wait for the program to finish executing before continuing to the next statement in your script. If set to true, script execution halts until the program finishes, and Run returns any error code returned by the program. If set to false (the default), the Run method returns immediately after starting the program, automatically returning 0 (not to be interpreted as an error code).

Remarks

The Run method returns an integer. The Run method starts a program running in a new Windows process. You can have your script wait for the program to finish execution before continuing. This allows you to run scripts and programs synchronously. Environment variables within the argument strCommand are automatically expanded. If a file type has been properly registered to a particular program, calling run on a file of that type executes the program. For example, if Word is installed on your computer system, calling Run on a *.doc file starts Word and loads the document. The following table lists the available settings for intWindowStyle .

Читайте также:  Линукс узнать характеристики материнской платы

Hides the window and activates another window.

Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.

Activates the window and displays it as a minimized window.

Activates the window and displays it as a maximized window.

Displays a window in its most recent size and position. The active window remains active.

Activates the window and displays it in its current size and position.

Minimizes the specified window and activates the next top-level window in the Z order.

Displays the window as a minimized window. The active window remains active.

Displays the window in its current state. The active window remains active.

Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.

Sets the show-state based on the state of the program that started the application.

Example 1

The following VBScript code opens a copy of the currently running script with Notepad.

В Copy Code

The following VBScript code does the same thing, except it specifies the window type, waits for Notepad to be shut down by the user, and saves the error code returned from Notepad when it is shut down.

В Copy Code

Example 2

The following VBScript code opens a command window, changes to the path to C:\ , and executes the DIR command.

Running vbscript in windows

This forum is closed. Thank you for your contributions.

Answered by:

Question

The command: cscript somescript.vbs

I have found that the outcome of running somescript.vbs might be different depending on how you run the script:

C:\windows\system32\cscript somescript.vbs (works great on a 64 bit server. )

C:\windows\sysWOW64\cscript somescript.vbs (Although the output is successful, this doesn’t actually run properly. no data returned)

— so SysWOW64 is there for 32 bit reasons. And I believe that I should be running the 64 bit version anyway. so why do I care? I care because if I want to automate this somescript.vbs, I will be using a 32 bit program like SMS to push the script out.

Читайте также:  У кого windows 10 стабильная

For example, I have the ability to push out a package through SMS 2003 or SCCM 2007. However, because SMS/SCCM client is 32-bit, it always attempts to implements the script using the sysWOW64 cscript.

I also have Symantec (Alteris) Wise package studio. however, here again, Wise is 32 bit. and I can’t get it to run the 64 bit vbscript.

So, I guess my question here is. how can I force 64 bit version of cscript (vbscript). It seems that when I try to launch cscript from a 32 bit program (like sms 2003 or Wise), the 32 bit version of the script is always ran.

Running vbscript from batch file

I just need to write a simple batch file just to run a vbscript. Both the vbscript and the batch file are in the same folder and is in the SysWOW64 directory as the vbscript can only be execute in that directory. Currently my batch file is as follows:

But the vbscript wasn’t executed and just the command prompt is open. Can anyone tell me how can i execute the vbscript when i run this batch file?

5 Answers 5

dp0 to get the path of the currently running batch file.

Edited to change directory to the VBS location before running

If you want the VBS to synchronously run in the same window, then

If you want the VBS to synchronously run in a new window, then

If you want the VBS to asynchronously run in the same window, then

If you want the VBS to asynchronously run in a new window, then

dp0necdaily.vbs» . Note there is no backslash between %

dp0 and necdaily.vbs . – Gras Double Apr 17 ’17 at 22:42

This is the command for the batch file and it can run the vbscript.

Batch files are processed row by row and terminate whenever you call an executable directly.
— To make the batch file wait for the process to terminate and continue, put call in front of it.
— To make the batch file continue without waiting, put start «» in front of it.

I recommend using this single line script to accomplish your goal:

(because this is a single line, you can use @ instead of @echo off)

If you believe your script can only be called from the SysWOW64 versions of cmd.exe, you might try:

If you need the window to remain, you can replace /c with /k

Оцените статью