Repository navigation
Description
Intro & context
Symlink target may be a relative path, which is then resolved by the filesystem as a relative path from parent directory of the symlink. Example:
We have the following 2 files:
Directory: D:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
la--- 2021-04-15 00:41 0 file_link.txt -> .\file.txt
-a--- 2021-04-15 00:41 0 file.txt
file_link.txt is a file symlink, which resolves to D:\test\file.txt. It might be created with New-Item -Type SymbolicLink .\file_link.txt -Target .\file.txt.
There's a difference between a symlink to a file and to a directory, and attempting to traverse a directory symlink pointing to a file does not work (and same for trying to read from a file symlink pointing to a directory).
To correctly create the symlink, PowerShell checks whether the target is a file or a directory. Originally, this check was broken for relative target paths, because the process-wide .NET working directory was used to resolve the target (so the above command would check for a target path like C:\Windows\System32\file.txt - that path doesn't exist, so pwsh defaults to creating a file symlink). This was supposedly fixed in #12797.
With this "fix", working directory of PowerShell is now used instead of the .NET working directory. This is however still incorrect, because we don't want to resolve the target relative to CWD, but relative to the symlink itself.
Reproduction
(I'll use D:/test as our testing directory to make it clear when I'm talking about absolute paths)
1)
mkdir D:/test
mkdir D:/test/dir
cd D:/
ni -Type SymbolicLink D:/test/dir_link -Target ./dir
Expected: directory symlink to D:/test/dir, with target ./dir
Got: file symlink to D:/test/dir, with target ./dir
The target type detection code checks the relative path ./dir (D:/dir), which doesn't exist, so the symlink incorrectly defaults to file symlink.
2)
mkdir D:/test
mkdir D:/test/dir
cd D:/test
ni -Type SymbolicLink D:/test/dir_link -Target ./dir
Expected: directory symlink to D:/test/dir, with target ./dir
Got: what I expected
Only difference from previous example is the cd D:/test on line 3. This correctly creates a directory symlink, because the code checks type of target for ./dir (D:/test/dir), which now matches the real target.
3)
mkdir D:/test/subdir
mkdir D:/test/item # <-- directory
ni D:/test/subdir/item # <-- file
cd D:/test
ni -Type SymbolicLink D:/test/subdir/item_link -Target ./item
Expected: file symlink to D:/test/subdir/item, with target ./item
Got: directory symlink D:/test/subdir/item, with target ./item
The the file D:/test/item is used for target check, it's a directory, so a directory symlink is created (but the actual target is D:/test/subdir/item, which is a file).
Proposed fixes
There are 2 possible correct behaviors I see here:
- Always resolve symlink target to an absolute path in
New-Item. This effectively prevents PowerShell from creating symlinks with relative paths to target. - Allow relative paths, but when checking for target type (file/directory), use the path
Join-Path $Path $Targetinternally, but still write$Targetas provided by user (relative) into the symlink itself. This is imo the better solution, allows the user to create symlinks with relative paths, but still correctly detects the type.
Environment data
Name Value
---- -----
PSVersion 7.2.0-preview.4
PSEdition Core
GitCommitId 7.2.0-preview.4
OS Microsoft Windows 10.0.19042
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
Activity
mklement0 commentedon Apr 15, 2021
Thanks for writing this up.
Re behavior 1. (resolving to full paths before creating the symlink):
We do not want this, because defining symlinks that reference their targets via relative paths is an important feature, which enables moving such symlinks - along with their targets - to a different location without breaking things.
Therefore - I agree with your preference - we want behavior 2.
With that in mind, we want:
preserving relative targets as specified in the symlink's actual definition (potentially after normalizing path separators to the platform-native form).
for the sake of validating the target on creation, an existence check relative to the symlink's directory.
Currently, such checks are not performed (in terms of resulting in errors), except if the target is specified as a full path AND that path starts with a nonexistent drive specification or a nonexistent UNC share.
Conversely, you may want to - by way of opt-in - create a symlink to a target that you know not to exist yet.
See New-Item symlinks cannot be created if destination (target) is non-existent or not accessible #9067 (comment) for a discussion of these issues.
mklement0 commentedon Apr 15, 2021
If this gets fixed as suggested, the following is a moot point, but just to prevent additional confusion:
#12797, which, as you state, was conceptually the wrong fix, only partially achieved what it tried to do: a target path such as
.\foois recognized as a relative path and resolved against$PWD, but the equivalentfoo(no.\prefix) is not, and is currently still resolved against the process' current directory ([Environment]::CurrentDirectory); see #15161 for a repro (since closed, because it will implicitly also be resolved by resolving this issue).daxian-dbw commentedon Jun 11, 2021
The Engine WG spent ~25 minutes discussing about this issue. We agreed that the proposed fix no.2 is reasonable (quoted below). Namely, a relative path specified for
-Targetshould be resolved using the path to the symbolic link, instead of powershell's current working directory.This makes sense because when accessing a file/directory symbolic that is associated with a relative path, such as
Get-Content <symlink>, the relative path is resolved using the symlink path. So, we should be consistent in resolving the target relative path when creating a symbolic link withNew-Item.This proposed fix would be a breaking change to PowerShell 7.1. It feels like the right thing to do, but we need to evaluate the impact before proceeding.
Interestingly, our discussion led to another idea when comparing
New-Itemwithmklink, which we want to throw out here for more discussion.When creating a symbolic using
mklink,mklinkdoesn't check the existence of the specified<target>path. It creates a file symbolic by default, and creates a directory symbolic when/dis specified.As is shown in the screenshot below,
myfolderis an existing directory, butmklink my-link c:\arena\tmp\test-2\myfoldercreates a file symbolic, even though the target path is an existing directory.So, maybe
New-Itemshould work similarly asmklinkin creating a symbolic link?- does not check on the existence of
targetpath- create file symbolic by default, and add a new
switchparameter for creating directory symbolicThis would be a breaking change too, in that if target points to an existing directory, a directory symbolic will be create with the current behavior, but a file symbolic will be created if we change to the
mklinkbehavior.iSazonov commentedon Jun 11, 2021
If it is a bug why we would say "breaking change"? :-)
dogancelik commentedon Aug 23, 2021
I was going to comment on #15750 but it was closed.
New-Item Junction example:
Pwsh version:
7.1.4PowerShell version:
5.1.19041.1023:Xiphoseer commentedon Jun 27, 2022
I ran into this regression today and found it rather tricky to find this issue because a lot of parts just work until they don't. I hope the following points help others find it more easily and deal with it:
..\(or../) are not supported by the current PowerShell implementation, but happen to work in many cases, specifically, when the path exists relative to the directory PowerShell was started in. (../<username>is a good candidate to check that, in console windows started in the home directory)../or.\at the start of the target path. Those are not the only valid relative paths. Instead, I'd argue that!System.IO.Path.IsPathRooted(strTargetPath)should be used.PowerShell/src/System.Management.Automation/namespaces/FileSystemProvider.cs
Lines 2408 to 2413 in 7dc4587
Path.Joincould be called unconditionally, because rooted paths just discard the first part of the join anyways.CreateSymbolicLink, there's a flag calledSYMBOLIC_LINK_FLAG_DIRECTORY, whose only effect is to switch the result ofGetFileAttributesAfromFILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_REPARSE_POINTtoFILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT. That's the reason PowerShell needs to figure out why that target is a directory in the first place, which isn't something Linux needs.Get-ChildItem symlink/subfolderthrough a symlink with the wrong attribute (adding to the confusion). The only thing that actually breaks is getting a handle to the target directory viaCreateFile. This could be considered a bug inside of windows (and breaks the way flutter detects invalid links on windows, which is how I got here in the first place)/with\because that causes different sets of errors if written to the repare point with un-normalized forward slashes.To summarize: If you need to work around this bug right now, just prefix all relative paths with
.\even if they start with..\already. This is both a regression in PowerShell from 5 to 7 (e.g.New-Item -ItemType SymbolicLink -Path "data" -Target "..\data"no longer works reliably) and an area of the operating system that still breaks in mysterious and under-documented ways if not handled right (e.g. creating symlinks using the Win32 api with forward slashes or pointing to the wrong type of filesystem entry)God-damnit-all commentedon Aug 20, 2022
Additionally, you need to be in the working directory you want to add the directory-based symbolic link to because PowerShell is currently detecting whether a path is a file or a folder based on your current working directory rather than relative to the new item's path.
Lastly, you have to use double-quotes, if the relative path is in single-quotes it won't work properly.
This is rather contrived, I wish there could just be a switch parameter to specify that it's a directory I want to make rather than a file, or maybe its own special type like 'SymbolicLinkDir'.
7 remaining items
Resolve symlink target relative to the symlink instead of the working…
kodra-dev commentedon Nov 21, 2024
Is there any solution to this? What's the true Powershell equivalent of
mklink /Dnow?msftrncs commentedon Nov 22, 2024
Ideally, PowerShell should still check the link type, and report errors if it finds the target but the type is wrong.
Also, there seems to be more wrong with the original fix than I found discussed here. Interactively, the previous fix seems to work as described using the CWD, but in a script, it does not appear to use the CWD to resolve the relative link. CD/Set-Location/Push-Location do not help the New-Item command correctly interpret the relative path and resolve the target. As long as the target is relative to the path PowerShell (pwsh.exe) was originally started in at the point the script was executed, then it works fine.
Edit: to note that Daniel Seiler (@Xiphoseer) 's reference to adding a ".\" to the relative path resolves the difference between interactive and script mode I mentioned above...
Resolve symbolic link target relative to the symbolic link instead of…
microsoft-github-policy-service commentedon Dec 3, 2024
📣 Hey Matěj Kafka (@MatejKafka), how did we do? We would love to hear your feedback with the link below! 🗣️
🔗 https://aka.ms/PSRepoFeedback
Resolve symbolic link target relative to the symbolic link instead of…