Why is PowerShell resolving paths from $home instead of the current directory?
Asked Answered
A

2

18

I expect this little powershell one liner to echo a full path to foo.txt, where the directory is my current directory.

[System.IO.Path]::GetFullPath(".\foo.txt")

But it's not. It prints...

C:\Documents and Settings\Administrator\foo.txt

I am not in the $home directory. Why is it resolving there?

Aesthetics answered 1/11, 2010 at 18:13 Comment(2)
you should be using Resolve-Path within powershell.Hermaphroditism
On some systems it returns relative to c:\Windows\system32.Handbreadth
S
21

[System.IO.Path] is using the shell process' current directory. You can get the absolute path with the Resolve-Path cmdlet:

Resolve-Path .\foo.txt
Sheritasherj answered 1/11, 2010 at 22:32 Comment(4)
This behaviour is unintuitive and inconsistent with every other shell-scripting system on the planet. Of course. Thank you StackOverflow users like Shay, for helping us mere humans understand Powershell!Currier
The drawback of Resolve-Path is that it can resolve only paths that actually exist.Thurgau
Ah. So to glob or expand a path you plan to create, you can not use it.Currier
If we want to resolve a path that doesn't exist yet, we can use [System.IO.Path]::Combine((Get-Location), $relativePath).Rowe
M
13

According to the documentation for GetFullPath, it uses the current working directory to resolve the absolute path. The powershell current working directory is not the same as the current location:

PS C:\> [System.IO.Directory]::GetCurrentDirectory()
C:\Documents and Settings\user
PS C:\> get-location

Path
----
C:\

I suppose you could use SetCurrentDirectory to get them to match:

PS C:\> [System.IO.Directory]::SetCurrentDirectory($(get-location))
PS C:\> [System.IO.Path]::GetFullPath(".\foo.txt")
C:\foo.txt
Mccrea answered 1/11, 2010 at 19:6 Comment(3)
I have my prompt function do this, updating the current working directory.Gambrill
This will only work if the current location is in the filesystem. Check $PWD.Provider.Name first.Deuterogamy
correct way without provider name checking: [Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPathHuman

© 2022 - 2024 — McMap. All rights reserved.