2

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.

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".

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
}
}
1
  • 1
    Ah, this is a simple one. Move the $i = 1 line to inside the ForEach loop. Commented Sep 8, 2016 at 18:02

2 Answers 2

1

You'll need to reset the counter:

$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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Moving my comment to an answer. You need to move the $i = 1 line to inside your ForEach loop as such:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.