Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include another powershell script file inside of another powershell script?

Tags:

powershell

Let's say I have a powershell script that contains a Powershell Hash at a relative path to my current path. Lets call it "name.ps1" and it contains:

$names = @{
   "bob" = "bobby"
   "john" = "jones"
   "danial" = "davis"
}

etc...

Now, I have another powershell script called "dosomething.ps1" that wants to import this file "../db/names.ps1" into the current powerscript file like an old style c-language include, something like this:

#include "../db/names.ps1"

write-host ("BOB: {0}" -f $names.bob)
write-host ("JOHN: {0}" -f $names.john)

How can I accomplish this in powershell?

like image 692
Bimo Avatar asked Dec 04 '20 19:12

Bimo


1 Answers

This is called "dot-sourcing" in PowerShell as you just use ". Path/to/.ps1" to run that file. Typically these files will contain custom functions that you want to use in parent script.

In the example below the "include" file is in same folder as PowerShell script that is being executed.

. "$PSScriptRoot\MyCoolFunctionsLibrary.ps1"

Just put this before any calls to functions within the "include" file

NOTE: If you want to pass objects from the include file, be sure to set the scope of those objects properly within that include file.

like image 63
WayneC Avatar answered Nov 04 '22 14:11

WayneC