Powershell 复制项目重命名如果文件存在 [英] Powershell Copy-Item Rename If File Exists

查看:79
本文介绍了Powershell 复制项目重命名如果文件存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在脚本中使用在本网站上找到的这段代码来复制 PST 文件并重命名副本.我的问题和我遇到的问题是,当它重命名 .pst 时,它会继续增加数字.

I am using this code I found on this site in a script to copy PST files and rename the duplicate. My question and the problem I am having with it is that when it renames the .pst it continues to increment the number.

例如,如果它找到一个名为test.pst"的文件,它将按原样复制它.如果它找到另一个名为test.pst"的文件,它将复制它并将其重命名为test-1.pst",这很好.但是,如果它找到两个名为test2.pst"的文件,它会将第一个文件复制为test2.pst"并将第二个文件复制并重命名为test2-2.pst"而不是test2-1.pst".

For example, if it finds a file named "test.pst" it will copy it as is. If it finds another file also named "test.pst", it will copy it and rename it "test-1.pst" which is fine. However, if it finds two files named "test2.pst" it will copy the first one as "test2.pst" and copy and rename the second one to "test2-2.pst" instead of "test2-1.pst".

对于如何修改我的代码,以便它开始用 1 对每个新的重复文件进行编号(test3-1.pst、test4-1.pst 等),您有什么建议吗?

Do you have any suggestions on how I can modify my code so that it will start numbering each new duplicate file with 1 (test3-1.pst, test4-1.pst, etc)?

$csv = import-csv .\test.csv
foreach ($line in $csv) {
New-Item c:\new-pst\$($line.username) -type directory

$dest = "c:\new-pst\$($line.username)"
$i=1

Get-ChildItem -Path $line.path -Filter *.pst -Recurse | ForEach-Object {


    $nextName = Join-Path -Path $dest -ChildPath $_.name

    while(Test-Path -Path $nextName)
    {
       $nextName = Join-Path $dest ($_.BaseName + "_$i" + $_.Extension)
       $i++  
    }

    $_ | copy-Item -Destination $nextName -verbose
}
}

推荐答案

您需要重置计数器:

$csv = import-csv .\test.csv
foreach ($line in $csv) {
    New-Item c:\new-pst\$($line.username) -type directory

    $dest = "c:\new-pst\$($line.username)"

    Get-ChildItem -Path $line.path -Filter *.pst -Recurse | ForEach-Object {
        $i=1 # Note the position of the initializer
        $nextName = Join-Path -Path $dest -ChildPath $_.name

        while(Test-Path -Path $nextName)
        {
           $nextName = Join-Path $dest ($_.BaseName + "_$i" + $_.Extension)
           $i++  
        }

        $_ | copy-Item -Destination $nextName -verbose
    }
}

这篇关于Powershell 复制项目重命名如果文件存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆