![](/img/trans.png)
[英]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.