[英]Powershell - getting the scriptname of calling script in dot-sourced function
[英]Determine if PowerShell script has been dot-sourced
从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-调用功能于共享的powershell的脚本/
检查$ 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
补充mjolinor的有用答案 :
TL;博士
$isDotSourced = $MyInvocation.InvocationName -eq '.' -or $MyInvocation.Line -eq ''
而$MyInvocation.InvocationName -eq '.'
主要是告诉你一个给定的脚本是否是点源的,有一个例外 :
[ 至少适用于PowerShell v3 ]
当您使用“ Debug > Run/Continue
( F5 )从Visual Studio代码或PowerShell ISE运行脚本时,它是隐式获取的,但$MyInvocation.InvocationName
包含完整的脚本文件名而不是.
但是,您可以通过检查$MyInvocation.Line
是否为空来检测此情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.