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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With