PowerShell hosting and $MyInvocation

Many PowerShell users utilize code as shown below to determine where the running script resides:

function get-scriptdirectory{
  $invocation=(get-variable MyInvocation -Scope 1).Value
  Split-Path $invocation.myinvocation.path
}

Unfortunately, if the script runs inside a custom host, such as PrimalScript’s internal host, for a good number of debuggers and the SAPIEN PowerShell host from the PrimalForms packager, the MyInvocation variable contains an empty path member.

There is no documented way to set MyInvocation from a custom host and any attempts contacting Microsoft in this matter only resulted in confirmation that any attempt to do so would be overwritten anyway.

It seems unreasonable to expect the PowerShell team to change the API anytime soon. And even then, changing the current behavior might prove undesirable since it could potentially break existing scripts.

That of course leaves everyone implementing a custom host with a dilemma. The SAPIEN PowerShell hosts now all contain a variable called $HostInvocation which has the same interface as MyInvocation and provides the desired information.

So if you are running your script inside any SAPIEN PowerShell host you can use code like this to determine where your script is:

function get-scriptdirectory{
  if($hostinvocation -ne null) {
    Split-Path $hostinvocation.MyCommand.path
  }
  else {
    $invocation=(get-variable MyInvocation -Scope 1).Value
    Split-Path $invocation.myinvocation.path
  }
}