2016-04-07 32 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个不同的文件,在不同的路径。我在考虑复制品有一些扩展名,这样它就不会覆盖已经存在的文件并在最后附加一个数字。 –

相关问题