Fix New-Item -ItemType Hardlink to resolve target to absolute path and not allow link to itself (#18634)

This commit is contained in:
Steve Lee
2022-12-13 22:09:28 +05:00
committed by GitHub
parent c3a080caf9
commit eb9ca7c351
3 changed files with 36 additions and 1 deletions
@@ -2251,6 +2251,13 @@ namespace Microsoft.PowerShell.Commands
}
else
{
// for hardlinks we resolve the target to an absolute path
if (!IsAbsolutePath(strTargetPath))
{
// there is already a check before here so that strTargetPath should only resolve to 1 path
strTargetPath = SessionState.Path.GetResolvedPSPathFromPSPath(strTargetPath).FirstOrDefault()?.Path;
}
exists = GetFileSystemInfo(strTargetPath, out isDirectory) != null;
}
}
@@ -2293,6 +2300,13 @@ namespace Microsoft.PowerShell.Commands
if (Force)
{
if (itemType == ItemType.HardLink && string.Equals(path, strTargetPath, StringComparison.OrdinalIgnoreCase))
{
string message = StringUtil.Format(FileSystemProviderStrings.NewItemTargetIsSameAsLink, path);
WriteError(new ErrorRecord(new InvalidOperationException(message), "TargetIsSameAsLink", ErrorCategory.InvalidOperation, path));
return;
}
try
{
if (!isSymLinkDirectory && symLinkExists)
@@ -328,7 +328,7 @@
<value>Maximum size for drive has been exceeded: {0}.</value>
</data>
<data name="SymlinkItemExists" xml:space="preserve">
<value>Cannot create symbolic link because the path {0} already exists.</value>
<value>Cannot create link because the path already exists: {0}.</value>
</data>
<data name="AlreadyListedDirectory" xml:space="preserve">
<value>Skip already-visited directory {0}.</value>
@@ -336,4 +336,7 @@
<data name="TargetCannotBeSubdirectoryOfSource" xml:space="preserve">
<value>Destination path cannot be a subdirectory of the source: {0}.</value>
</data>
<data name="NewItemTargetIsSameAsLink" xml:space="preserve">
<value>The target and path cannot be the same.</value>
</data>
</root>
@@ -600,6 +600,24 @@ Describe "Hard link and symbolic link tests" -Tags "CI", "RequireAdminOnWindows"
New-Item -ItemType Junction -Path $junctionToDir -Value $realDir > $null
Test-Path $junctionToDir | Should -BeTrue
}
It 'New-Item can create hardlink with relative path' {
try {
Push-Location $TestDrive
1 > 1.txt
New-Item -ItemType HardLink -Path 2.txt -Target 1.txt -ErrorAction Stop
$hl = Get-Item -Path .\2.txt -ErrorAction Stop
$hl.LinkType | Should -BeExactly "HardLink"
}
finally {
Pop-Location
}
}
It 'New-Item will fail to forcibly create hardlink to itself' {
$i = New-Item -ItemType File -Path "$TestDrive\file.txt" -Force -ErrorAction Ignore
{ New-Item -ItemType HardLink -Path $i -Target $i -Force -ErrorAction Stop } | Should -Throw -ErrorId "TargetIsSameAsLink,Microsoft.PowerShell.Commands.NewItemCommand"
}
}
Context "Get-ChildItem and symbolic links" {