Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if PowerShell script has been dot-sourced

Tags:

powershell

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/

like image 606
Paolo Tedesco Avatar asked Feb 02 '11 14:02

Paolo Tedesco


People also ask

What is PowerShell dot sourcing?

The dot sourcing feature lets you run a script in the current scope instead of in the script scope. When you run a script that is dot sourced, the commands in the script run as though you had typed them at the command prompt.

What is a .ps1 file?

A PS1 file is a script, or "cmdlet," used by Windows PowerShell, a Windows shell program built on Microsoft's . NET Framework. It contains a series of commands written in the PowerShell scripting language.

Where are PowerShell scripts stored?

PowerShell scripts can be created within PowerShell Universal to execute manually, on a scheudle or when events happen within the platform. They are stored on disk and also persisted to a local or remote Git repository. Script properties are stored in the scripts. ps1 configuration file.


2 Answers

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

like image 125
mjolinor Avatar answered Oct 21 '22 10:10

mjolinor


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.

like image 29
mklement0 Avatar answered Oct 21 '22 08:10

mklement0