开发者

Copy folder using Copy-Item - different behaviour

I want copy whole folder to another folder using Copy-Item.

My source folder c:\base contains some files:

├───base    
│       file1.txt
│       file2.txt

I use the following command:

Copy-Item c:\base c:\target -recurse

if the target folder (c:\target) exists, the command copies source folder exactly as I want:

├───target
│   └───base    
│           file1.txt
│           file2.txt

If the target folder doesn't exist, the command creates target folder (exactly as I want), but now it copies only the content of the source folder (without the base folder):

├───target    
│       file1.t开发者_运维问答xt
│       file2.txt
  • Why does it happen?
  • How can I use this copy command (additional keys?) without create the target folder before?


It is a known bug ( feature some would say):

http://groups.google.com/group/microsoft.public.windows.powershell/msg/3327f2d1544e7fb6?as_umsgid=6CAEDDC7-0F1A-4B21-8FB0-E6102A16EB51@microsoft.com

This behaviour IMO, is an artifiact of the provider and object pipeline model that powershell uses. You have to get used to the idea that the navigational context is a bit weird compared to other shells; it's explicit as opposed to implicit, since the filesystem is one of many contexts that can be used. This brings with it some weird behaviours since the targets of any given path are handled with a combination of powershell's generic grammar and the command itself, as opposed to being entirely handled by the command in shells like command.com/cmd.exe.


Yeah, this one is a really nasty.

If you want to have a consistent copy experience, use this pattern:

$copyFrom = 'C:\Foo\Bar\TargetDirectoryToCopy'
$destinationPath = 'D:\Bar\Foo\'

$newItemParams = @{
    Path        = $destinationPath
    ItemType    = 'Directory'
    Force       = $True
}

$copyParams = @{
    Path        = $copyFrom
    Destination = $destinationPath
    Recurse     = $True
    Confirm     = $false
    Force       = $True
}
New-Item @newItemParams
Copy-Item @copyParams

Result

The directory D:\Bar\Foo\ will have TargetDirectoryToCopy directory nested inside.

So if there is a file C:\Foo\Bar\TargetDirectoryToCopy\FooBar.txt, its copy will be created as D:\Bar\Foo\TargetDirectoryToCopy\FooBar.txt along with any another file in C:\Foo\Bar\TargetDirectoryToCopy

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜