Don't allow Move-Item with FileSystemProvider to move a directory into itself (#16198)

This commit is contained in:
Steve Lee 2021-10-12 14:16:32 -07:00 committed by GitHub
parent 329250c974
commit d0e823797f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 0 deletions

View file

@ -5851,6 +5851,15 @@ namespace Microsoft.PowerShell.Commands
destination = MakePath(destination, dir.Name);
}
// Don't allow moving a directory into itself
if (destination.StartsWith(Path.TrimEndingDirectorySeparator(path) + Path.DirectorySeparatorChar))
{
string error = StringUtil.Format(FileSystemProviderStrings.TargetCannotBeSubdirectoryOfSource, destination);
var e = new IOException(error);
WriteError(new ErrorRecord(e, "MoveItemArgumentError", ErrorCategory.InvalidArgument, destination));
return;
}
// Get the confirmation text
string action = FileSystemProviderStrings.MoveItemActionDirectory;

View file

@ -345,4 +345,7 @@
<data name="AlreadyListedDirectory" xml:space="preserve">
<value>Skip already-visited directory {0}.</value>
</data>
<data name="TargetCannotBeSubdirectoryOfSource" xml:space="preserve">
<value>Destination path cannot be a subdirectory of the source: {0}.</value>
</data>
</root>

View file

@ -187,6 +187,20 @@ Describe "Basic FileSystem Provider Tests" -Tags "CI" {
$e.Exception | Should -BeOfType System.IO.IOException
}
It 'Verify Move-Item fails for destination that is subdir of source with trailing: <trailingChar>' -TestCases @(
@{ trailingChar = [System.IO.Path]::DirectorySeparatorChar }
@{ trailingChar = [System.IO.Path]::AltDirectorySeparatorChar }
@{ trailingChar = '' }
) {
param($trailingChar)
$dest = Join-Path -Path $TestDrive -ChildPath dest
$null = New-item -ItemType Directory -Path $dest -Force -ErrorAction Stop
$src = "$TestDrive$trailingChar"
{ Move-Item -Path $src -Destination $dest -ErrorAction Stop } | Should -Throw -ErrorId 'MoveItemArgumentError,Microsoft.PowerShell.Commands.MoveItemCommand'
}
It "Verify Move-Item throws correct error for non-existent source" {
{ Move-Item -Path /does/not/exist -Destination $testFile -ErrorAction Stop } | Should -Throw -ErrorId 'PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand'
}