7

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?

SteveC
  • 15,808
  • 23
  • 102
  • 173
Sitaram Pamarthi
  • 445
  • 3
  • 5
  • 14

3 Answers3

7

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.

Richard
  • 106,783
  • 21
  • 203
  • 265
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).

Winfred
  • 940
  • 1
  • 8
  • 23
0

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'
Francisco
  • 169
  • 2
  • 11