I grok it
I grok it

Reputation: 65

UpperCase only first two letters of all filenames in a folder?

I know I can convert all filenames in a given folder to uppercase with the following:

Get-ChildItem -Path your_path -Recurse | Rename-item -NewName {$_.name.ToUpper()}

However, how can I capitalize only the first two letters of all filenames in a folder?

i.e.

ls123456_This_is_a_Test.pdf --> LS123456_This_is_a_Test.pdf

re98765_Another_Test.pdf --> RE98765_Another_Test.pdf

Thanks Dan

Upvotes: 3

Views: 1346

Answers (2)

user6811411
user6811411

Reputation:

Use the .SubString() method to separate the first two characters

## Q:\Test\2018\07\21\SO_51451148.ps1
$Folder = (Get-Item '.').FullName
Get-ChildItem -Path $Folder -File -Recurse |
 Where-Object Name -match '^[a-z]{2}.' |
   Rename-item -NewName {"{0}{1}" -f $_.Name.SubString(0,2).ToUpper(),
                                     $_.Name.Substring(2)} -WhatIf

If the output looks OK, remove the -WhatIf parameter

Upvotes: 6

Esperento57
Esperento57

Reputation: 17462

try it :

Get-ChildItem "c:\temp" -file  | %{

    if ($_.Name.Length -gt 1)
    {
        $NewName="{0}{1}" -f $_.Name.SubString(0, 2).ToUpper(), $_.Name.Substring(2)
    }
    else
    {
        $NewName=$_.Name.ToUpper()
    }

    Rename-item $_.FullName $NewName -WhatIf

}

Upvotes: 1

Related Questions