确定PowerShell脚本是否已经过点源

时间:2011-02-02 14:57:45

标签: powershell

从PowerShell脚本中,我如何确定脚本是否已经过点源,即已使用

调用脚本
. .\myscript.ps1

而不是

.\myscript.ps1

注意一篇有趣的博文(也):http://poshoholic.com/2008/03/18/powershell-deep-dive-using-myinvocation-and-invoke-expression-to-support-dot-sourcing-and-direct-invocation-in-shared-powershell-scripts/

2 个答案:

答案 0 :(得分:12)

检查$ myinvocation.line 它将显示用于调用脚本的行。

 PS C:\scripts\test> gc test.ps1
 $myinvocation.line

 PS C:\scripts\test> ./test.ps1
 ./test.ps1

 PS C:\scripts\test> . ./test.ps1
 . ./test.ps1

您还可以检查.invocationname属性。如果脚本是点源的,它只是一个点。如果没有,那将是./scriptname.ps1

答案 1 :(得分:9)

补充mjolinor's helpful answer

<强> TL;博士

$isDotSourced = $MyInvocation.InvocationName -eq '.' -or $MyInvocation.Line -eq ''

虽然$MyInvocation.InvocationName -eq '.' 主要告诉您某个给定的脚本是否为点源,但有一个异常

[至少适用于PowerShell v3 ] 当您从 Visual Studio代码运行脚本或使用Debug > Run/Continue F5 )运行 PowerShell ISE 时,它是隐式的 来源,但$MyInvocation.InvocationName包含完整的脚本文件名而不是.但是,您可以通过检查$MyInvocation.Line是否为空来检测此情况。< / p>