简体   繁体   中英

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

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.

使用与使用dot-operator相同的语法,就像获取文件一样:

. My-Function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM