Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell equivalent of python's if __name__ == '__main__':

I am really fond of python's capability to do things like this:

if __name__ == '__main__':
    #setup testing code here
    #or setup a call a function with parameters and human format the output
    #etc...

This is nice because I can treat a Python script file as something that can be called from the command line but it remains available for me to import its functions and classes into a separate python script file easily without triggering the default "run from the command line behavior".

Does Powershell have a similar facility that I could exploit? And if it doesn't how should I be organizing my library of function files so that i can easily execute some of them while I am developing them?

like image 333
Mark Mascolino Avatar asked Jan 14 '11 17:01

Mark Mascolino


3 Answers

$MyInvocation.Invocation has information about how the script was started.

If ($MyInvocation.InvocationName -eq '&') {
    "Called using operator: '$($MyInvocation.InvocationName)'"
} ElseIf ($MyInvocation.InvocationName -eq '.') {
    "Dot sourced: '$($MyInvocation.InvocationName)'"
} ElseIf ((Resolve-Path -Path $MyInvocation.InvocationName).ProviderPath -eq $MyInvocation.MyCommand.Path) {
    "Called using path: '$($MyInvocation.InvocationName)'"
}
like image 152
Bacon Bits Avatar answered Oct 24 '22 03:10

Bacon Bits


$MyInvocation has lots of information about the current context, and those of callers. Maybe this could be used to detect if a script is being dot-sourced (i.e. imported) or executed as a script.

A script can act like a function: use param as first non-common/whitespace in the file to defined parameters. It is not clear (one would need to try different combinations) what happens if you dot-source a script that starts param...

Modules can directly execute code as well as export functions, variables, ... and can take parameters. Maybe $MyInvocation in a module would allow the two cases to be detected.

EDIT: Additional:

$MyInvocation.Line contains the command line used to execute the current script or function. Its Line property has the scrip text used for the execution, when dot-sourcing this will start with "." but not if run as a script (obviously a case to use a regex match to allow for variable whitespace around the period).

In a script run as a function

like image 6
Richard Avatar answered Oct 24 '22 01:10

Richard


As of now I see 2 options that work

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

and

if ($MyInvocation.CommandOrigin -eq 'Runspace') {#do main stuff}
like image 2
esac Avatar answered Oct 24 '22 03:10

esac