title: How to recursively truncate filenames in powershell?
body: <p>I need to truncate filenames to 35 characters (including extension) so I run this script and it worked for the directory it self (PowerShell, Windows 10).</p>
  
  <pre><code>Get-ChildItem *.pdf | rename-item -NewName {$_.name.substring(0,31) + $_.Extension} 
  </code></pre>
  
  <p>Then I wanted to apply the same script including subdirectories:</p>
  
  <pre><code>Get-ChildItem -Recurse -Include *.pdf | Rename-Item -NewName {$_.Name.substring(0,31) + $_.Extension}
  </code></pre>
  
  <p>This script gave me an error like this for each file:</p>
  
  <pre><code>Rename-Item : Error in input to script block for parameter 'NewName'. Exception when calling "Substring" with the arguments "2": "The index and length must reference a location in the string. Parameter name: length"
  On line: 1 Character: 62
  + ... *.pdf | Rename-Item -NewName {$_.Name.substring(0,31) + $_.Extension}
  +                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidArgument: (C:\User\prsn..._file_name_long.pdf:PSObject) [Rename-Item], ParameterBindingException
      + FullyQualifiedErrorId : ScriptBlockArgumentInvocationFailed,Microsoft.PowerShell.Commands.RenameItemCommand
  </code></pre>
  
  <p>I tried this one but it doesn't go on subdirectories:
  <a href="https://stackoverflow.com/questions/811607/command-to-truncate-all-filenames-at-255-characters">Command to truncate all filenames at 255 characters</a></p>
  
  <p>I found this one but it doesn't have an answer:
  <a href="https://superuser.com/questions/1188711/how-to-recursively-truncate-filenames-and-directory-names-in-powershell">https://superuser.com/questions/1188711/how-to-recursively-truncate-filenames-and-directory-names-in-powershell</a></p>