Search code examples
powershellfile-renamebatch-rename

Remove all characters after specific character in multiple filenames


how do I remove every character after a _ in folder names ex folder names 307456_ajksndkajsdna_asd_busd to 307456

780451_dsadafg_4565 to 780451

edit: also remove the _ I am using windows 7


Solution

  • In PowerShell, you can use the -split operator to split the string by _ and keep only the first part:

    $number,$null = '307456_ajksndkajsdna_asd_busd' -split '_'
    

    The value of $number is now 307456, the rest has been discarded.

    If you want to rename all child folders in a folder to just the first number, use Get-ChildItem to retrieve the files, and Rename-Item to rename them:

    Get-ChildItem -Path C:\folder\name |Where-Object {$_.PSIsContainer} |Rename-Item -NewName { $($_.Name -split '_')[0] }