mao
7/6/2017 - 9:15 AM

Check invocation method inside script. Answers question "How do I check inside script if it was called or dot sourced?"

Check invocation method inside script. Answers question "How do I check inside script if it was called or dot sourced?"

<#    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"
          }
        }
      )
"@

}