Last active
July 8, 2017 23:35
-
-
Save turboBasic/50220884e3367c133e2e1157fe9b03eb to your computer and use it in GitHub Desktop.
Check invocation method inside script. Answers question "How do I check inside script if it was called or dot sourced?"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# Determine invocation method: . | & | <script path > | |
https://poshoholic.com/2008/03/18/powershell-deep-dive-using-myinvocation-and-invoke-expression-to-support-dot-sourcing-and-direct-invocation-in-shared-powershell-scripts/ | |
if ($MyInvocation.InvocationName -eq '&') { | |
"Called using operator" | |
} elseif ($MyInvocation.InvocationName -eq '.' -or $MyInvocation.Line -eq '') { | |
"Dot sourced" | |
} elseif ((Resolve-Path -Path $MyInvocation.InvocationName).ProviderPath -eq $MyInvocation.MyCommand.Path) { | |
"Called using path $($MyInvocation.InvocationName)" | |
} | |
#> | |
function PrintSomething { | |
PARAM( | |
[String] | |
$Name = "I am a `$Name in PrintSomething()" | |
) | |
'I am PrintSomething()' | |
$Name | |
} | |
if ($MyInvocation.InvocationName -ne '.' -and $MyInvocation.Line -ne '') { | |
Invoke-Expression @" | |
PrintSomething $( | |
$passThruArgs = $Args | |
foreach ($argument in $passThruArgs) { | |
if ($argument -match '^-') { | |
$argument | |
} else { | |
"$argument" | |
} | |
} | |
) | |
"@ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment