Filename Truncation In Directory

This topic contains 7 replies, has 4 voices, and was last updated by Profile photo of Olaf Soyk Olaf Soyk 1 month, 2 weeks ago.

  • Author
    Posts
  • #55498
    Profile photo of H-D
    H-D
    Participant

    I have been searching around and haven't found the exact PowerShell command that I think I need. I am completely new to Powershell but have some programming background. I am looking for a simple PowerShell code that will act on all files in a directory and truncate the filename beyond a specific amount of characters. I find all over the internet where the last part of the file is kept while truncating the first part of the file but I'm looking to do the opposite. So, for example, the code I've come across for doing the opposite on a file like "test file_w.xyz" would look like this to get "w.xyz":

    gci *.xyz | rename-item -newname {[string]($_.name).substring($_.name.length -5)}

    I'm looking for something similar only instead of say "length -5" to have something like "length +9" to get me the filename
    "test file.xyz" truncating the "_w".

    My exact situation is always knowing a fixed set of characters at the beginning of the filename but beyond my fixed number the character count can vary...In which case those characters get cut off the filename.

    Any help would be appreciated. Thanks.

  • #55508
    Profile photo of Olaf Soyk
    Olaf Soyk
    Participant
  • #55727
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    Keep in mind that you should consider testing if files exist before renaming. Take a look at a basic example just testing that your parsing is working before you attempt rename operations:

    $files = Get-ChildItem -Path "C:\Users\Rob\Desktop\Archive\Temp\*.xyz"
    $files | Select BaseName, Extension, @{Name="ParsedName";Expression={"{0}{1}" -f $_.BaseName.SubString(0,9), $_.Extension}}
    
  • #55754
    Profile photo of H-D
    H-D
    Participant

    Thank you all for the quick replies and help. Based on Olaf's links I modified the above code to this:

    gci *.xyz |rename-item -newname {[string]($_.name).substring(0,9)}

    However, this strips off the file extensions. Is there an easy way to add that back on with the above code?

    Thanks again.

  • #55762
    Profile photo of H-D
    H-D
    Participant

    Thanks again. It appears all I need to do is the following to get the extensions back:

    gci *.xyz |rename-item -newname {[string]($_.name).substring(0,9) +".xyz"}

    ...in case someone is looking for a compact way to do something similar...

    • #55774
      Profile photo of Olaf Soyk
      Olaf Soyk
      Participant

      H-D,

      hmmmm .... even if that does the job in this particular case because you're just treating files with the same extension. That's not what I wanted to show to you. If you want to handle different file types you will need a little more sofisticated approach.
      As of in Powershell is actually everything an object you can use this for your good and let powershell do the magic for you.
      Let's pick a file from your windows and try to figure out what information we can get and use:

      $path = 'C:\Windows\notepad.exe'
      Get-Item -Path $path | Select-Object -Property *
      
      PSPath            : Microsoft.PowerShell.Core\FileSystem::C:\Windows\notepad.exe
      PSParentPath      : Microsoft.PowerShell.Core\FileSystem::C:\Windows
      PSChildName       : notepad.exe
      PSDrive           : C
      PSProvider        : Microsoft.PowerShell.Core\FileSystem
      PSIsContainer     : False
      Mode              : -a---l
      VersionInfo       : File:             C:\Windows\notepad.exe
                          InternalName:     Notepad
                          OriginalFilename: NOTEPAD.EXE.MUI
                          FileVersion:      6.1.7601.17514 (win7sp1_rtm.101119-1850)
                          FileDescription:  Editor
                          Product:          Betriebssystem Microsoft® Windows®
                          ProductVersion:   6.1.7601.17514
                          Debug:            False
                          Patched:          False
                          PreRelease:       False
                          PrivateBuild:     False
                          SpecialBuild:     False
                          Language:         Deutsch (Deutschland)
      
      BaseName          : notepad
      Target            : {C:\Windows\winsxs\amd64_microsoft-windows-notepadwin_31bf3856ad364e35_6.1.7601.18917_none_a0f2c3fc11a9f24c\notepad.exe}
      LinkType          : HardLink
      Name              : notepad.exe
      Length            : 193536
      DirectoryName     : C:\Windows
      Directory         : C:\Windows
      IsReadOnly        : False
      Exists            : True
      FullName          : C:\Windows\notepad.exe
      Extension         : .exe
      CreationTime      : Do 04.02.2016 10:00:09
      CreationTimeUtc   : Do 04.02.2016 09:00:09
      LastAccessTime    : Do 04.02.2016 10:00:09
      LastAccessTimeUtc : Do 04.02.2016 09:00:09
      LastWriteTime     : Do 04.02.2016 10:00:09
      LastWriteTimeUtc  : Do 04.02.2016 09:00:09
      Attributes        : Archive
      

      As you can see Powershell gives you a cornucopia of information. And you don't have to do that much for it. And of course you can use all these information at your will. If you want to rename some files but the extension should stay the same you just 'save' it before you rename the file and attach it afterwards. Just as Mohit Goyal showed.

      If all that information is too confusing or needless you just pick what you need

      Get-Item -Path $path | Select-Object -Property Directory, BaseName, Extension
      
      Directory  BaseName Extension
      ---------  -------- ---------
      C:\Windows notepad  .exe

      Now you have exactly what you need to rename any file.

      AND I would urgently recommend you to read this post: How to Format Code in the Forums and if you have a little more time left to improve your Powershell skills you can watch this: (I think it's really entertaining) Time to Get Serious

      Have a nice Weekend and a lot of fun

  • #55765
    Profile photo of mohit goyal
    mohit goyal
    Participant

    You should be using something like this:

    Get-ChildItem "E:\ttt" | rename-item -newname {[string]($_.basename).substring(0,9) + $_.Extension}
    

You must be logged in to reply to this topic.