2016-04-07 36 views
0

我正在運行一個PowerShell腳本,使用以下內容:在Powershell中,如果文件已存在,如何複製/粘貼文件以滾動文件的新副本?

Copy-Item -Path c:\ Windows \ Microsoft.NET \ Framework \ v2.0.50727 \ CONFIG \ machine.config -Destination c:\ Windows \ Microsoft。 NET \ Framework \ v2.0.50727 \ CONFIG \ machine.orig

如果machine.orig已經存在,我怎樣才能將它複製到machine.orig1,如果已經存在,machine.orgin2?

回答

2

複製這樣的文件如果我可以提一個建議。就我個人而言,我喜歡文件上的日期/時間標記,而不是增量編號。通過這種方式,您可以知道文件的備份時間,並且您不太可能對文件造成混淆。再加上腳本代碼更簡單。

希望這會有所幫助。

$TimeStamp = get-date -f "MMddyyyyHHmmss" 
$SourceFile = Dir c:\folder\file.txt 
$DestinationFile = "{0}\{1}_{2}.{3}" -f $SourceFile.DirectoryName, $SourceFile.BaseName, $TimeStamp, $SourceFile.Extension 
copy-Item $sourcefile $DestinationFile 
+0

嗯,這可能不是一個壞主意,我會試試看。我只提到了增量數字(並且謝謝你說增量數字,我想不起這個詞),因爲它很快就可以了。我會試試這個,讓你知道。 –

+0

非常感謝你吉恩,這正是我所需要的,它的工作非常好。這對我來說已經解決了。 –

+0

我還會補充一點,我覺得這個解決方案更舒服,因爲移動部件更少,再次感謝 –

0
#let us first define the destination path 
$path = "R:\WorkindDirectory" 
#name of the file 
$file = "machine.orgin" 
#let us list the number of the files which are similar to the $file that you are trying to create 
$list = Get-ChildItem $path | select name | where name -match $file 
#let us count the number of files which match the name $file 
$a = ($list.name).count 
#if such count of the files matching $file is less than 0 (which means such file dont exist) 
if ($a -lt 1) 
{ 
New-Item -Path $path -ItemType file -Name machine.orgin 
} 
#if such count of the files matching $file is greater than 0 (which means such/similar file exists) 
if ($a -gt 0) 
{ 
$file = $file+$a 
New-Item -Path $path -ItemType file -Name $file 
} 

注意:這項工作假定文件的名稱是串聯的。讓我們說使用這個腳本創建 machine.orgin

machine.orgin1

machine.orgin2

machine.orgin3

,之後再刪除machine.orgin2並重新運行相同的腳本,然後它不會工作。 在這裏,我給在那裏我曾試圖創建一個新的文件的例子,你可以安全地修改同使用copy-item代替new-item

+0

謝謝Gajendra,這是很好的信息,現在的問題是,我正在做這4個不同的文件,在不同的路徑。我在考慮複製品有一些擴展名,這樣它就不會覆蓋已經存在的文件並在最後附加一個數字。 –

相關問題