Determine if PowerShell script has been dot-sourced

北慕城南 提交于 2019-12-19 05:14:57

问题


From a PowerShell script, how can I determine if the script has been dot-sourced, i.e. it has been called with

. .\myscript.ps1

rather than

.\myscript.ps1

NOTE an interesting blog post (also) about this: 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/


回答1:


Check $myinvocation.line It will show the line that was used to call the script.

 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

You can also check the .invocationname property. If the script was dot-sourced, it will just be a dot. If not, is will be ./scriptname.ps1




回答2:


To complement mjolinor's helpful answer:

tl;dr

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

While $MyInvocation.InvocationName -eq '.' mostly tells you whether a given script is being dot-sourced, there is one exception:

[Applies as of at least PowerShell v3]
When you run a script from Visual Studio Code or the PowerShell ISE with Debug > Run/Continue (F5), it is implicitly sourced, yet $MyInvocation.InvocationName contains the full script filename rather than . However, you can detect this case by checking if $MyInvocation.Line is empty.



来源:https://stackoverflow.com/questions/4875912/determine-if-powershell-script-has-been-dot-sourced

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!