为防止概念混淆:
为了对脚本进行点源,即直接在调用者的作用域中执行它(与默认的子作用域相反),以便调用者看到脚本的变量、函数定义……:
在当前的PowerShell 会话.
中,直接使用dot-sourcing 运算符:
# Dot-source in the caller's scope.
# When executed at the prompt in an interactive PowerShell session,
# the script's definitions become globally available.
. '.\dot-source-test.ps1'
通过Windows PowerShell CLIpowershell.exe
[ 1]:
场景 A:预加载定义,执行依赖它们的命令,然后退出:
以下启动一个(新的)PowerShell 会话,如下所示:
PS> powershell -c '. .\dot-source-test.ps1; $theValue'
theValue
场景 B:使用预加载的定义进入(新的)交互式会话:
只需添加-noexit
开关以进入脚本文件已被点源的交互式会话:.\dot-source-test.ps1
powershell -noexit -c '. .\dot-source-test.ps1'
# You're now in a (new) interactive session in which $theValue is defined,
# and which you must eventually exit manually.
笔记:
[1] 这同样适用于PowerShell [Core] 7+ CLI pwsh
,除了它默认为-File
而不是
-Command
.