0

I found a way to get the current working directory into $dp0.

PS C:\src\powershell> Get-Content .\curdir2.ps1
$dp0 = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)

Set-Location -Path $dp0
Write-Host "location is set"

Set-Location -Path [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)

Write-Host (Get-Location).Path

Why is it that when I try to use the same way as a parameter to Set-Location it is an error? I think this may be something fundamental about the objects in Powershell. What do I need to know?

Set-Location : A positional parameter cannot be found that accepts argument 'C:\src\powershell\curdir2.ps1'.
At C:\src\powershell\curdir2.ps1:6 char:1
+ Set-Location -Path [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.De ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-Location], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
0

1 Answer 1

2

Use parentheses.
As you can see in PS ISE that entire parameter is interpreted as a literal string otherwise.
And always use -LiteralPath instead of -Path to correctly handle directories with [] brackets.

Set-Location -LiteralPath ([IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition))

PS3.0+: cd -LiteralPath $PSScriptRoot

Sign up to request clarification or add additional context in comments.

2 Comments

I am giving you the check mark. Can you say anything more about why parentheses are needed? I do not think I have ever seen that in other languages.
PowerShell syntax is quite weird because it treats unquoted text as strings for parameters of string and string[] (array of strings) types. And just like inside a string it only recognizes the variables $var and expressions $(....). Bare parentheses are basically a shorthand of the latter when no quotes are used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.