Search code examples
powershellrename-item-cmdlet

PowerShell Rename-Item on Long Named Files Warning Removal


I try to rename files with PwerShell Rename-Item cmdlet. Code below

Get-ChildItem -recurse * `
  | ?{!$_.PsIsContainer} `
  | Rename-Item -NewName {$_.FullName -Replace '[email protected]','.abcd@email_A.com.abcd@email_B.com.abcd@email_E.com'}

But, PowerShel tells me about long path or file name; which is irrelevant to my process. But it is strongly necessary keep new long name.

How to except this error?


Solution

  • is it possible ask you about code example? The following commented code snippet (conservative approach) could help:

    Get-ChildItem -recurse * | Where-Object {!$_.PsIsContainer} | 
      ForEach-Object {
        ###  in regular expression:  ↓           ↓   escape dots
        $NewName = $_.Name -Replace '\.abcd@email\.com',
          '.abcd@email_A.com.abcd@email_B.com.abcd@email_E.com'
    
        ### here is right place to check target filename length:
        $targetLength = 1 + $_.DirectoryName.Length + $NewName.Length
    
        Rename-Item -Path $_.FullName -NewName $NewName
      }
    

    Read Rename-Item reference and Regular Expression Language - Quick Reference.