2017-02-27 81 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

相關問題