Fix New-Item to work correctly when given path is drive root and $PWD is a sub folder of the drive root. (#6600)

This commit is contained in:
Matthew Bobke 2018-04-25 14:32:58 -07:00 committed by Dongbo Wang
parent a9781dedc2
commit 35d8de927b
2 changed files with 53 additions and 8 deletions

View file

@ -2013,6 +2013,9 @@ namespace System.Management.Automation
// Check to see if the path is relative or absolute
bool isPathForCurrentDrive = false;
// Check to see if the path is to the root of a drive
bool isPathForRootOfDrive = false;
if (IsAbsolutePath(path, out driveName))
{
Dbg.Diagnostics.Assert(
@ -2080,6 +2083,12 @@ namespace System.Management.Automation
// this is the default behavior for all windows drives, and all non-filesystem
// drives on non-windows
path = path.Substring(driveName.Length + 1);
if (String.IsNullOrEmpty(path))
{
// path was to the root of a drive such as 'c:'
isPathForRootOfDrive = true;
}
}
}
}
@ -2111,14 +2120,23 @@ namespace System.Management.Automation
// have access to it.
context.Drive = workingDriveForPath;
string relativePath =
GenerateRelativePath(
workingDriveForPath,
path,
escapeCurrentLocation,
providerInstance,
context);
string relativePath = String.Empty;
if (isPathForRootOfDrive)
{
relativePath = context.Drive.Root;
}
else
{
relativePath =
GenerateRelativePath(
workingDriveForPath,
path,
escapeCurrentLocation,
providerInstance,
context);
}
return relativePath;
}
catch (PSNotSupportedException)

View file

@ -117,6 +117,33 @@ Describe "New-Item" -Tags "CI" {
$fileInfo.Target | Should -BeNullOrEmpty
$fileInfo.LinkType | Should -BeExactly "HardLink"
}
It "Should create a file at the root of the drive while the current working directory is not the root" {
try {
New-Item -Name $testfolder -Path "TestDrive:\" -ItemType directory > $null
Push-Location -Path "TestDrive:\$testfolder"
New-Item -Name $testfile -Path "TestDrive:\" -ItemType file > $null
$FullyQualifiedFile | Should -Exist
}
finally {
Pop-Location
}
}
It "Should create a folder at the root of the drive while the current working directory is not the root" {
$testfolder2 = "newDirectory2"
$FullyQualifiedFolder2 = Join-Path -Path $tmpDirectory -ChildPath $testfolder2
try {
New-Item -Name $testfolder -Path "TestDrive:\" -ItemType directory > $null
Push-Location -Path "TestDrive:\$testfolder"
New-Item -Name $testfolder2 -Path "TestDrive:\" -ItemType directory > $null
$FullyQualifiedFolder2 | Should -Exist
}
finally {
Pop-Location
}
}
}
# More precisely these tests require SeCreateSymbolicLinkPrivilege.
@ -186,7 +213,7 @@ Describe "New-Item with links" -Tags @('CI', 'RequireAdminOnWindows') {
}
It "New-Item -ItemType SymbolicLink should understand directory path ending with slash" {
$folderName = [System.IO.Path]::GetRandomFileName()
$folderName = [System.IO.Path]::GetRandomFileName()
$symbolicLinkPath = New-Item -ItemType SymbolicLink -Path "$tmpDirectory/$folderName/" -Value "/bar/"
$symbolicLinkPath | Should -Not -BeNullOrEmpty
}