To complement [mjolinor's helpful answer](
[To see links please register here]
):
**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**:
When you run a script from the - obsolescent<sup>[1]</sup> - **Windows PowerShell ISE** with `Debug > Run/Continue` (<kbd>F5</kbd>), 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_.
(The PIC (PowerShell Integrated Console) that comes with [**Visual Studio Code**](
[To see links please register here]
)'s [PowerShell extension](
[To see links please register here]
) _used to_ behave this way, but as of at least version v2023.1.0 submits explicit dot-sourcing commands).
Note: Detecting whether a _function_ is being dot-sourced is _not_ subject to the exception above, so testing for `$MyInvocation.InvocationName -eq '.'` is sufficient (but the above will work too).
---
<sup>[1] The PowerShell ISE is [no longer actively developed](
[To see links please register here]
) and [there are reasons not to use it](
[To see links please register here]
) (bottom section), notably not being able to run [*PowerShell (Core) 7+*](
[To see links please register here]
). The actively developed, cross-platform editor that offers the best PowerShell development experience is [Visual Studio Code](
[To see links please register here]
) with its [PowerShell extension](
[To see links please register here]
).
</sup>