Newby question about grabbing current path

Welcome Forums General PowerShell Q&A Newby question about grabbing current path

This topic contains 3 replies, has 2 voices, and was last updated by

 
Participant
1 week, 4 days ago.

  • Author
    Posts
  • #156686

    Participant
    Topics: 2
    Replies: 2
    Points: 14
    Rank: Member

    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: (:) [Split-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.SplitPat
    hCommand

  • #156690

    Participant
    Topics: 1
    Replies: 1333
    Points: 1,690
    Helping Hand
    Rank: Community Hero

    You have to run this as script. If you don't have a script you don't have a script path. 😉

  • #156696

    Participant
    Topics: 2
    Replies: 2
    Points: 14
    Rank: Member

    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

  • #156702

    Participant
    Topics: 1
    Replies: 1333
    Points: 1,690
    Helping Hand
    Rank: Community Hero

    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.

You must be logged in to reply to this topic.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort