Newby question about grabbing current path

Hi folks, I’m trying to run the following commands and, by golly, I’m missing something because my variable is returning NULL. Thanks for any guidance you can provide!

$scriptpath = $MyInvocation.MyCommand.Path
write-host ("Script Path is: " + $scriptpath)
$dir = Split-Path $scriptpath
write-host ("Dir is: " + $dir)

This is what I see in the console:

PS C:\Coding\PowerShell> $scriptpath = $MyInvocation.MyCommand.Path
PS C:\Coding\PowerShell> write-host ("Script Path is: " + $scriptpath)
Script Path is:
PS C:\Coding\PowerShell> $dir = Split-Path $scriptpath
Split-Path : Cannot bind argument to parameter ‘Path’ because it is null.
At line:1 char:19

  • $dir = Split-Path $scriptpath
  • CategoryInfo : InvalidData: (:slight_smile: [Split-Path], ParameterBindingValidationException
  • FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.SplitPat
    hCommand

You have to run this as script. If you don’t have a script you don’t have a script path. :wink:

Thanks Olaf. So if I’m working from the console and not a script I guess I could do something like this:

PS C:\Coding\PowerShell> $testpath = (Get-Location).path
PS C:\Coding\PowerShell> $testpath
C:\Coding\PowerShell

But is there another preferred method? Thanks for your time.

 

Ryan

You don’t have to do that by yourself.
Powershell has some predefined variables you don’t have to create explicitly. $PWD for the current working directory … you can use interactively in the console and $PSScriptRoot for the directory of the script you’re running.

You can read more about this with Get-Help about_Automatic_Variables.