Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a PowerShell script from another one

Tags:

powershell

What is the best and correct way to run a PowerShell script from another one?

I have a script a.ps1 from which I want to call b.ps1 which does different task.

Let me know your suggestions. Is dot sourcing is the best option here?

like image 535
Sitaram Pamarthi Avatar asked Apr 05 '11 09:04

Sitaram Pamarthi


People also ask

How do I run one PowerShell script from another?

You don't need Start-Process. PowerShell scripts can run other scripts. Just put the command that runs the second script as a command in the first script (the same way as you would type it on the PowerShell command line). You can experiment with this very easily by doing a quick test.

How do I run a PowerShell script from the path?

To run a script, type the full name and the full path to the script file. To run a script in the current directory, type the path to the current directory, or use a dot to represent the current directory, followed by a path backslash ( . \ ).

How do I run a ps1 script from the command line?

ps1 files are interpreted by PowerShell, the Command Prompt (CMD) cannot work with PowerShell scripts directly. If you would like to run a PowerShell script in CMD, you'll need to execute it by calling the PowerShell process with the -File parameter, as shown below: PowerShell -File C:\TEMP\MyNotepadScript. ps1.


2 Answers

Dot sourcing will run the second script as if it is part of the caller—all script scope changes will affect the caller. If this is what you want then dot-source,

However it is more usual to call the other script as if it were a function (a script can use param and function level attributes just like a function). In many ways a script is a PowerShell function, with the name of the file replacing the naming of the function.

like image 180
Richard Avatar answered Nov 14 '22 22:11

Richard


Dot sourcing makes it easier to at a later stage convert your script(s) into a module, you won't have to change the script(s) into functions.

Another advantage of dot sourcing is that you can add the function to your shell by adding the file that holds the functions to Microsoft.PowerShell_profile.ps1, meaning you have them available at all times (eliminating the need to worry about paths etc).

I have a short write-host at the top of my dot sourced files with the name of the function and common parameters and I dot source the functions in my profile. Each time I open PowerShell, the list of functions in my profile scrolls by (If like me, you frequently forget the exact names of your functions/files You'll appreciate this as over time as the number of functions start to pile up).

like image 22
Winfred Avatar answered Nov 14 '22 21:11

Winfred