2017-02-27 41 views
4

这似乎是一个微不足道的问题,并多次回答。我仍然不清楚。如何重命名/移动项目并覆盖即使存在(对于文件,文件夹和链接)?

一个命令与强制覆盖,做工作的任何项目类型(叶,容器)移动项目(或只是重命名为源和目标是一个文件夹中)?

背景:我正在编写一个脚本,用相应的符号链接替换所有硬链接和连接。示例代码:

mkdir C:\Temp\foo -ErrorAction SilentlyContinue 
'example' > C:\Temp\foo\bar.txt 
cd C:\Temp 
New-Item -ItemType Junction -Name bar -Target C:\Temp\foo 
New-Item -ItemType SymbolicLink -Name bar2 -Target '.\foo' 

#produces error: Rename-Item : Cannot create a file when that file already exists. 
Rename-Item -Path 'C:\Temp\bar2' -newName 'bar' -force 

#unexpected behaviour: moves bar2 inside bar 
Move-item -Path 'C:\Temp\bar2' -destination 'C:\Temp\bar' -force 

#this works as per https://github.com/PowerShell/PowerShell/issues/621 
[IO.Directory]::Delete('C:\Temp\bar') 
Rename-Item -Path 'C:\Temp\bar2' -newName 'bar' 

回答

0

我认为你要找的是具有覆盖文件和合并目录选项的UI体验。这些只是复杂的错误处理机制,以解决您所看到的同样的错误,这要感谢微软的深思熟虑的工程师。

mkdir C:\Temp\foo -ErrorAction SilentlyContinue 
'example' > C:\Temp\foo\bar.txt 
cd C:\Temp 
New-Item -ItemType Junction -Name bar -Target C:\Temp\foo 
New-Item -ItemType SymbolicLink -Name bar2 -Target '.\foo' 

#produces error: Rename-Item : Cannot create a file when that file already exists. 
Rename-Item -Path 'C:\Temp\bar2' -newName 'bar' -force 

这是有道理的。您有两个不同的对象,因此它们不能具有相同的标识符。这就好比试图指向两个不同的对象

#unexpected behaviour: moves bar2 inside bar 
Move-item -Path 'C:\Temp\bar2' -destination 'C:\Temp\bar' -force 

这并不意外。当您为目的地指定一个目录时,它将它视为移动项目应放置在其中的目标目录。

#this works as per https://github.com/PowerShell/PowerShell/issues/621 
[IO.Directory]::Delete('C:\Temp\bar') 
Rename-Item -Path 'C:\Temp\bar2' -newName 'bar' 

这基本上是什么周到微软的工程师们通过他们的合并文件夹和覆盖文件的用户界面为你做。

Note that this is the same behavior for the .Net method in System.IO as well

+0

当这些是自然的目标目录时合并目录是很好的。说到符号链接和连接时,这有点不必要。 –

+0

另一个原因是,当您尝试创建两个具有相同名称的对象时,除了抛出异常外,操作系统不会执行任何操作。你需要/去决定以编程方式做什么。 – NonSecwitter

相关问题