Why $PSCommandPath is $null in ISE or PowerGUI

Welcome Forums General PowerShell Q&A Why $PSCommandPath is $null in ISE or PowerGUI

This topic contains 1 reply, has 2 voices, and was last updated by

5 years, 7 months ago.

  • Author
  • #13308

    Topics: 108
    Replies: 186
    Points: 12
    Rank: Member


    I'm trying to figure out how to find out where my script is located at the time of execution and from what I researched so far it seems to have been a problem with PS for sometime. I'm running PS 4.0 and inside ISE as well as inside PowerGui when I access $PSCommandPath variable in debug mode it always $null. The same variable works fine if I just use Write-Host $PSCommandPath.
    What I want to do is to supply certain default values for parameters like below to inform script where to look for some resource files. It works with $pwd variable but not with $PSCommandPath. How do I reliably access variable informing me where is my script is located which I'm debugging or running?

    [string]$OutputFile = "$PSCommandPath\output_$(Get-Date -Format ('yyyy_dd_MM_hh_mm')).log",


  • #13310

    Topics: 9
    Replies: 2322
    Points: 0
    Rank: Member

    You can't use certain automatic variables in your param block (such as $PSCommandPath, $MyInvocation, $PSCmdlet, etc); they don't work the way you'd expect them to.

    Instead, you can move that logic inside the script or function itself. For example:

    param (
        [string]$OutputFile = $null
    if (-not $OutputFile)
        $OutputFile = "$PSCommandPath\output_$(Get-Date -Format yyyy_dd_MM_hh_mm).log"

The topic ‘Why $PSCommandPath is $null in ISE or PowerGUI’ is closed to new replies.