【问题标题】:In Powershell, how do I copy/paste a file, if file already exists, to roll the new copy of the file?在 Powershell 中,如果文件已存在,如何复制/粘贴文件以滚动文件的新副本?
【发布时间】:2016-04-07 15:59:11
【问题描述】:

我正在运行一个 powershell 脚本,带有以下内容

复制项目 - 路径 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?

【问题讨论】:

    标签: powershell copy paste overwrite


    【解决方案1】:

    如果我可以提出建议。就个人而言,我喜欢文件上的日期/时间戳而不是增量数字的想法。这样您就可以知道文件的备份时间,并且您对文件感到困惑的可能性要小得多。加上脚本代码更简单。

    希望这会有所帮助。

    $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
    

    【讨论】:

    • 嗯,这可能不是一个坏主意,我会试一试。我只提到了增量数字(也感谢您说增量数字,我想不出这个词),因为它很快。我会试试这个,让你知道。
    • 非常感谢 Gene,这正是我所需要的,而且效果很好。这已为我解决。
    • 我还要补充一点,我觉得这个解决方案更舒服,因为活动部件更少,再次感谢
    【解决方案2】:
    #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 复制此类文件

    【讨论】:

    • 谢谢 Gajendra,这是很好的信息,现在的问题是我正在对 4 个不同路径的不同文件执行此操作。我在想 copy-item 有某种扩展名来做到这一点,这样它就不会覆盖已经存在的文件并在末尾附加一个数字。
    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多