我正在使用以下
运行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?
答案 0 :(得分: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
答案 1 :(得分: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
来复制这样的文件