All PowerShell scripts have a default variable called $myinvocation
.
Here’s the variable for a script I run directly:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
MyCommand : defaultvars.ps1 BoundParameters : {} UnboundArguments : {} ScriptLineNumber : 1 OffsetInLine : 18 HistoryId : 5 ScriptName : Line : .\defaultvars.ps1 PositionMessage : At line:1 char:18 + .\defaultvars.ps1 <<<< InvocationName : .\defaultvars.ps1 PipelineLength : 1 PipelinePosition : 1 ExpectingInput : False CommandOrigin : Runspace |
And here’s the variable for a script I dot-source:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
MyCommand : defaultvars.ps1 BoundParameters : {} UnboundArguments : {} ScriptLineNumber : 1 OffsetInLine : 2 HistoryId : 6 ScriptName : Line : . .\defaultvars.ps1 PositionMessage : At line:1 char:2 + . <<<< .\defaultvars.ps1 InvocationName : . PipelineLength : 1 PipelinePosition : 1 ExpectingInput : False CommandOrigin : Runspace |
So if you want to check whether a script was dot-source or not check $myinvocation.InvocationName
. If dot-sourced that would be a dot.