This topic contains 3 replies, has 2 voices, and was last updated by
May 15, 2019 at 2:04 pm #156686ParticipantTopics: 2Replies: 2Points: 14Rank: 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
May 15, 2019 at 2:10 pm #156690ParticipantTopics: 1Replies: 1333Points: 1,690Rank: Community Hero
You have to run this as script. If you don't have a script you don't have a script path. 😉
May 15, 2019 at 2:27 pm #156696ParticipantTopics: 2Replies: 2Points: 14Rank: 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
But is there another preferred method? Thanks for your time.
May 15, 2019 at 3:17 pm #156702ParticipantTopics: 1Replies: 1333Points: 1,690Rank: 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.