title: Get script directory in PowerShell when script is invoked with Invoke-Command
body: <p>I have a set of PowerShell scripts that include a "common" script, located in the same folder, like this:</p>
  
  <pre><code># some-script.ps1
  $scriptDir = Split-Path -Parent $myinvocation.mycommand.path
  . "$scriptDir\script-utils.ps1"
  </code></pre>
  
  <p>This is fine if the script is called directly, e.g.</p>
  
  <pre><code>.\some-script.ps1
  </code></pre>
  
  <p>However, if the script is called with Invoke-Command, this does not work:</p>
  
  <pre><code>Invoke-Command -ComputerName server01 -FilePath "X:\some-script.ps1"
  </code></pre>
  
  <p>In this case, infact, <code>$myinvocation.mycommand</code> contains the contents of the script, and <code>$myinvocation.mycommand.path</code> is null.<br>
  How can I determine the script's directory in a way that works also when the script is invoked with Invoke-Command?</p>
  
  <p><strong>NOTE</strong><br>
  In the end, this is the solution I actually used:</p>
  
  <pre><code>Invoke-Command -ComputerName server01 `
    {param($scriptArg); &amp; X:\some-script.ps1 $scriptArg } `
    -ArgumentList $something
  </code></pre>
  
  <p>This also allows passing parameters to the script.</p>