3

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

Community
  • 1
  • 1
Josh Petitt
  • 9,371
  • 12
  • 56
  • 104
  • 1
    [about_Scopes](http://technet.microsoft.com/en-us/library/hh847849.aspx) – Anthony Neace Mar 10 '14 at 20:10
  • @HyperAnthony thanks for the link. Is there a equivalent one-liner for PowerShell to the python version? I understand that PowerShell scripts are ran from top to bottom. So I'd like to put a test condition near the bottom of my script that only if it passes, does the remainder of the script run. – Josh Petitt Mar 10 '14 at 20:19

1 Answers1

5

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.

mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • thank you, this seems to be good information. Do you know if the $myinvocation.CommandOrigin would give me what I want? My preliminary testing seems to show 'Runspace' if I started the script from powershell, and 'Internal' if another script is calling it? I have not found any detailed info on the CommandOrigin member. – Josh Petitt Mar 10 '14 at 20:43
  • I also see the InvocationName which seems to be either a '.' or the name of the script? Maybe this is a better way? – Josh Petitt Mar 10 '14 at 20:46
  • 1
    I don't know Python, so I'm not quite sure what to tell you to look for that would be the analog of that Python command. – mjolinor Mar 10 '14 at 20:51
  • Thanks! Every scope gets initialized with it's own $args, so it should always be there :). – mjolinor Mar 13 '14 at 12:24