Why doesn't Write-Host "$PSCommandPath" output my current path?

output, path, powershell

Solution

If I had to guess, you are running an older version of PowerShell that does not support `$PSCommandPath`. The variable is only available in versions 3.0 and newer. From the documentation:

`$PSCommandPath`

Contains the full path and name of the script that is being run. This parameter is valid in all scripts. This automatic variable is introduced in Windows PowerShell 3.0.

So, like all undefined variables, `$PSCommandPath` is being treated as `$null`:

PS > ($undefined).GetType()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ ($undefined).GetType()
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull


PS > 
PS > $var = 123
PS > Write-Host "My variable: $var"
My variable: 123

PS > Write-Host "My variable: $undefined"
My variable: 

PS > 

To fix the problem, you need to upgrade PowerShell to version 3.0 or newer.

Also, it seems like you actually want `Get-Location`, which returns the current working directory:

Write-Host "Current directory is... $(Get-Location)"

Problem

I have the following bit of code- ``` Set-Location "$PSCommandPath" Write-Host "Starting script." Write-Host "Current directory is... $PSCommandPath" ``` Which just returns- ``` Starting script. Current directory is... ``` How do I remedy this?

Original source