Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: How to source a function like source a file?

Tags:

powershell

In my main script, I will first call an init function to initiate many variables which I expected to be used in the script. One way is to use variables whose name are like $script:var1 which are script level variable. But that's kind of ugly and I'd like to use normal variable name, so I need a mechanism to source a function just like source a file.

When source a file, all the variables in that file are available in the calling script.

like image 972
Daniel Wu Avatar asked Jan 22 '11 07:01

Daniel Wu


2 Answers

Use the same syntax that uses dot-operator, just like for sourcing files:

. My-Function
like image 165
Roman Kuzmin Avatar answered Sep 28 '22 05:09

Roman Kuzmin


You can also do it in a scriptblock and dot-source that, but the rules are slightly different. You must have a space after the period to dot-source a function, and you don't with a scriptblock.

Both of these will produce 42

$a=0
function init {$a=42}
. init
$a

$a=0 
$init={$a=42}
.$init
$a
like image 44
mjolinor Avatar answered Sep 28 '22 06:09

mjolinor