在 Powershell 中,如果文件已存在,我如何 copy/paste 滚动文件的新副本?

In Powershell, how do I copy/paste a file, if file already exists, to roll the new copy of the file?

我是运行一个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?

#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

来复制此类文件

如果我可以提个建议。就个人而言,我喜欢文件上的 date/time 标记而不是递增数字。这样您就可以知道文件何时备份,并且您 运行 不太可能对文件感到困惑。再加上脚本代码更简单

希望对您有所帮助。

$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