Powershell Copy-Item重命名如果文件存在

时间:2016-09-08 17:47:11

标签: powershell

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

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

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

$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
}
}

2 个答案:

答案 0 :(得分:1)

您需要重置计数器:

$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
    }
}

答案 1 :(得分:0)

将我的评论移至答案。您需要将$i = 1行移至ForEach循环内:

$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

    $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
}
}
相关问题