8

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?

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Please note, you will need to use the full or relative path to the script, unless it is on the system path.
1

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).

Comments

1

Old but still relevant. I work with modules with "Import-Module ", this will import the module in the current powershell session. To avoid keep in cache and to always have the last changes from the module I put a "Get-Module | Remove-Module" that will clear all the loaded modules in the current session.

Get-Module | Remove-Module
Import-Module '.\IIS\Functions.psm1'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.