Windows call script from script

Call script from Windows command line

Is it possible to call a script in Digital Micrograph from the Windows command line? I cannot seem to find information on command line options, if any are available, for DM.

2 Answers 2

No, this is not possible for GMS version 2 or lower. There are no command-line parameters for script-launch in DigitalMicrograph.

However, if you want to run a script automatically on start-up of DM, you can do this by installing a script as plugin (.gtk file).

From GMS 3.0.1 onward, there is an optional start-up parameter for the application.

You can type (in the command prompt):

to launch the script test.s within the application.

Similar, you can type things like

DigitalMicrograph.exe /es «scriptcommand»

to directly execute the script-line scriptcommand within the application.

Unfortunately, earlier version of GMS do not have this option.

Note: When you call DigitalMicrograph.exe while the application is already running, it will not start the program again but instead activate the already running application. Therefore this can be used to launch a script in an already running application.

This also opens a nice way to run DM-scripts from a different editor like NotePad++.

In NotePad++ you can configure a «run» command. If you press F5 you specify a command to be called. So to have this run a DM script, use a line like the following:

You can then execute a script writtin within NotePad++ simply by selecting this run.

What is the best way to call a script from another script?

I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.

File test1.py :

File service.py :

I’m aware of one method which is opening the file, reading the contents, and basically evaluating it. I’m assuming there’s a better way of doing this. Or at least I hope so.

13 Answers 13

The usual way to do this is something like the following.

This is possible in Python 2 using

See the documentation for the handling of namespaces, if important in your case.

In Python 3, this is possible using (thanks to @fantastory)

However, you should consider using a different approach; your idea (from what I can see) doesn’t look very clean.

File test1.py:

File service.py:

The advantage to this method is that you don’t have to edit an existing Python script to put all its code into a subroutine.

If you want test1.py to remain executable with the same functionality as when it’s called inside service.py, then do something like:

Using os you can make calls directly to your terminal. If you want to be even more specific you can concatenate your input string with local variables, ie.

You should not be doing this. Instead, do:

Use import test1 for the 1st use — it will execute the script. For later invocations, treat the script as an imported module, and call the reload(test1) method.

  • Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called
Читайте также:  Ubuntu windows 10 где лежат файлы

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

I want call execution for a myScript1.ps1 script inside a second myScript2.ps1 script inside Powershell ISE.

The following code inside MyScript2.ps1, works fine from Powershell Administration, but doesn’t work inside PowerShell ISE:

I obtain the following error when I execute MyScript2.ps1 from PowerShell ISE:

The term ‘.\myScript1.ps1’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

11 Answers 11

In order to find the location of a script, use Split-Path $MyInvocation.MyCommand.Path (make sure you use this in the script context).

The reason you should use that and not anything else can be illustrated with this example script.

Here are some results.

In PowerShell 3.0 and later you can use the automatic variable $PSScriptRoot :

I am calling myScript1.ps1 from myScript2.ps1 .

Assuming both of the script are at the same location, first get the location of the script by using this command :

And, then, append the script name you want to call like this :

This should work.

The current path of MyScript1.ps1 is not the same as myScript2.ps1. You can get the folder path of MyScript2.ps1 and concatenate it to MyScript1.ps1 and then execute it. Both scripts must be in the same location.

One line solution:

This is just additional info to answers in order to pass argument into the another file

Where you expect argument

PrintName.ps1

How to call the file

If you do not do not provide any input it will default to «Joe» and this will be passed as argument into printName argument in PrintName.ps1 file which will in turn print out the «Joe» string

You may have found the answer for it already, but here is what I do.

I usually place this line at the beginning of my installation scripts:

Then I can use $PSScriptRoot variable as a location of the current script(path), like in the example bellow:

In your case, you can replace

Start-process. line with

To execute easily a script file in the same folder (or subfolder of) as the caller you can use this:

I had a problem with this. I didn’t use any clever $MyInvocation stuff to fix it though. If you open the ISE by right clicking a script file and selecting edit then open the second script from within the ISE you can invoke one from the other by just using the normal .\script.ps1 syntax. My guess is that the ISE has the notion of a current folder and opening it like this sets the current folder to the folder containing the scripts. When I invoke one script from another in normal use I just use .\script.ps1, IMO it’s wrong to modify the script just to make it work in the ISE properly.

I had a similar problem and solved it this way.

My working directory is a general script folder and serveral particular script folder in same root, i need to call particular script folder (which call general script with the parameter of the particular problem). So working directory is like this

Solutions1 and Solutions2 call the PS1 in Scripts folder loading the parameter stored in ParameterForSolution. So in powershell ISE i run this command

Читайте также:  Драйвер для d link dwa 140 для windows 10

And the code inside Solution1.PS1 is:

I submit my example for consideration. This is how I call some code from a controller script in the tools I make. The scripts that do the work also need to accept parameters as well, so this example shows how to pass them. It does assume the script being called is in the same directory as the controller script (script making the call).

The above is a controller script that accepts 3 parameters. These are defined in the param block. The controller script then calls the script named Get-ZAEventLogData.ps1. For the sake of example, this script also accepts the same 3 parameters. When the controller script calls to the script that does the work, it needs to call it and pass the parameters. The above shows how I do it by splatting.

How do you run PowerShell built-in scripts inside of your scripts?

How do you use built-in scripts like

Those are ran by your computer, automatically checking the path of the script.

Similarly, I can run my custom scripts by just putting the name of the script in the script-block

Go on to the powershell command line and type

This will return the path to a file that our PowerShell command line will execute every time you open the app.

It will look like this

Go to Documents and see if you already have a WindowsPowerShell directory. I didn’t, so

We’ve now created the script that will launch every time we open the PowerShell App.

The reason we did that was so that we could add our own folder that holds all of our custom scripts. Let’s create that folder and I’ll name it «Bin» after the directories that Mac/Linux hold its scripts in.

Now we want that directory to be added to our $env:path variable every time we open the app so go back to the WindowsPowerShell Directory and

Now the shell will automatically find your commands, as long as you save your scripts in that «Bin» directory.

Relaunch the powershell and it should be one of the first scripts that execute.

Run this on the command line after reloading to see your new directory in your path variable:

Now we can call our scripts from the command line or from within another script as simply as this:

As you see we must call them with the .ps1 extension until we make aliases for them. If we want to get fancy.

Основы языка JScript — написание WSH скриптов

Сегодня поговорим об очень полезном компоненте операционной системы Windows — это Windows Script Host, если быть конкретней, то о языке Jscript, на котором можно писать эти самые WSH скрипты.

Начнем мы с небольшой теории, так как мы еще не затрагивали Windows Script Host.

Что такое Windows Script Host?

Windows Script Host – сервер выполнения сценариев (скриптов) на таких языках как VBScript и JScript. WSH разработан компанией Microsoft и он является компонентом операционной системы Windows начиная с Windows 98.

Первоначально для администрирования использовались только bat-файлы, но их возможности ограничены (хотя также очень полезны!), поэтому компания Microsoft предложила такой вариант WSH. Возможности WSH-скриптов уже гораздо больше, ведь данные скрипты уже создаются на полноценных языках, таких как VBScript и JScript.

Именно о JScript мы сегодня и поговорим.

Но о VBScript мы тоже скажем пару слов.

VBScript – это скриптовой язык программирования, созданный компанией Microsoft для разработки скриптов в операционной системе Windows. Другими словами, это один из языков, которые может интерпретировать Windows Script Host. И из названия ясно, что VBScript основан на языке Visual Basic, поэтому тем, кто знаком с Visual Basic будет просто писать WSH-скрипты на этом языке программирования.

Читайте также:  Как установить linux ubuntu с уже установленной windows

JScript – скриптовой язык программирования, с помощью которого можно создавать (писать) скрипты, которые будут интерпретироваться компонентом Windows Script Host.

С первого взгляда JScript во многом похож на JavaScript (ECMAScript), это и естественно, так как синтаксис, некоторый объекты, методы, свойства аналогичны JavaScript. Но это все же не JavaScript, а именно JScript. JavaScript (ECMAScript) ориентирован на объекты браузера, а JScript уже на компоненты операционной системы Windows. Но как мы сказали, они похожи, поэтому те, кто владеют языком программирования JavaScript с легкостью перейдут на JScript.

Возможности Windows Script Host

А теперь давайте поговорим о том, зачем нам нужно писать эти самые WSH-скрипты, т.е. об их возможностях и преимуществах:

  • Возможность взаимодействия с файловой системой (файлы, каталоги), системным реестром, ресурсами локальной сети;
  • Взаимодействие с такими продуктами как Microsoft Word, Excel и другими программами. Т.е. например, мы можем создавать excel файлы или конвертировать другие форматы в excel файлы;
  • Взаимодействие с ActiveX-технологиями, например: ActiveX Data Object (ADO) — доступ к базам данных разных форматов, Active Directory Service Interface (ADSI) — работа со службами каталогов Active Directory;
  • Наличие полноценного языка программирования, с помощью которого можно реализовывать сложные алгоритмы, которые например нельзя реализовать с помощью bat файлов.

Скрипты на JScript имеют расширение .js такое же, как и на JavaScript за исключением того, что эти скрипты обрабатывает не браузер, а Windows Script Host.

На JScript возможно даже реализация графического интерфейса через объект браузера (internet explorer), согласитесь это уже полноценная программа.

Примеры написания WSH скриптов

Перейдем к практике, так как у нас сегодня статья по основам, мы рассмотрим простые примеры написание скриптов на JScript.

Примечание! Для того чтобы попробовать примеры ниже скопируйте код любого примера в текстовый файл и сохраните с расширением .js, например, test.js.

Выводим сообщение на JScript

В WSH имеется специальный объект, на основе которого мы уже можем в дальнейшем создавать другие объекты, настраивать взаимодействие с программами, файлами и другими компонентами операционной системы.

Этим объектом является WScript. Пример его использования на Jscript:

Тем самым мы создали объект, с помощью которого мы можем получить доступ к компонентам Windows.

Например, вывести сообщение:

Работа с Excel на JScript

Теперь давайте создадим другой объект, например, Excel файл:

Как Вы понимаете, мы имеем доступ ко всем свойствам в Excel, другими словами, мы можем изменить внешний вид, задать формат ячеек и многое другое. Для примера давайте поэкспериментируем с некоторыми свойствами:

Работа с текстовым файлом и Excel на JScript

Я думаю с Excel все понятно, теперь давайте прочитаем какие-нибудь данные из текстового файла и запишем их в нашу Excel таблицу, для закрепления наших знаний.

Для того чтобы настроить взаимодействие с файловой системой, необходимо создать объект FileSystemObject, который работает с файлами и каталогами. Вот пример небольшого скрипта, который считывает данные из текстового файла построчно и записывает их в Excel документ, причем мы все строки пронумеруем и зададим ширину столба для данных в Excel:

Пример текстового файла:

Как всегда весь код я прокомментировал, поэтому неясностей возникнуть не должно.

Я думаю для начала этого вполне достаточно, в дальнейшем мы будем разбирать задачи посложней, ведь при помощи Jscript в WSH можно очень много чего сделать, гораздо больше, чем с помощью простых bat файлов. До встречи!

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