Add filename increment in my script

Viewed 1297

I have created a script that will rename pst files to acl owner. It works. The only problem i have is when there are two pst files in the same folder.It gives them the same name. How can i add an increment in my script. It ried it with Si = 1 and Si++ but with no results.

Here is my script:

Get-ChildItem C:\Users\tester\* -Filter *.pst -recurse |
    ForEach-Object{
        $owner = ( $_ | Get-Acl ).Owner.Split("\")[1]
        $newname = "$owner.pst"
        $_ | Rename-Item -NewName $newname -Verbose -WhatIf
    }
2 Answers

This is a quick and fast work around by adding names already used to an array and checking each time you loop.

$increment = 1
$alreadyProcessed = @()    
Get-ChildItem C:\Users\tester\* -Filter *.pst -recurse |
        ForEach-Object{
            $owner = ( $_ | Get-Acl ).Owner.Split("\")[1]
            $newname = "$owner.pst"
            if($alreadyProcessed.Contains($newName))
            {
                $newName = "$owner`$increment.pst"
                $increment++
            }
            $alreadyProcessed += $newname

            $_ | Rename-Item -NewName $newname -Verbose -WhatIf
        }

This will ensure a unique name each time.

If you plan to run your script multiple times in the same place then you should check to see what names are available otherwise your counter will reset to 1 but those files would already exist.

function Get-NextName ($file) {

    $existing = (Get-Item "$file.*").Name
    $i = 1

    while ($existing -contains "$file.$i") {
        $i++
    }

    "$file.$i"
}

And then adjust your function:

Get-ChildItem C:\Users\tester\* -Filter *.pst -recurse |
    ForEach-Object{
        $owner = ( $_ | Get-Acl ).Owner.Split("\")[1]
        $newname = Get-NextName "$owner.pst"
        $_ | Rename-Item -NewName $newname -Verbose -WhatIf
    }
Related