Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if Powershell script started in main scope?

I am a beginner Powershell user. I am writing some script files (.ps1)

I would like to determine how my script was invoked:

Was is the "main" script or was it dot sourced from another file?

In python, I would use something like:

if __name__ == "__main__":

Is there something similar in PowerShell?

Update

After reading the answers, I am using the following at the end of my .ps1 file:

if ($MyInvocation.InvocationName -ne '.')
{
  # do "main" stuff here
}

Any answers that include how this could fail are welcome.

It appears this is a duplicate question, I just didn't use the right search terms: Determine if PowerShell script has been dot-sourced

like image 844
Josh Petitt Avatar asked Jul 06 '26 16:07

Josh Petitt


1 Answers

If you're wanting to know how it was invoked, have a look at the $myinvocation automatic variable.

If you just want to test if you're in the global scope:

Try {if (get-variable args -scope 1){$true}}
Catch {$false}

should return $true if you're running in a child scope. If you're already in the global scope, there is no parent scope and it will throw an error and return $false.

like image 111
mjolinor Avatar answered Jul 08 '26 20:07

mjolinor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!