0

Can "Rename-Item" be used for stripping the filename without extension only to leave couple of characters on the beginning of the filename?

for ex. "0001 filename.txt" > "0000.txt"

Rayearth
  • 222
  • 1
  • 3
  • 20

4 Answers4

1

You could use a combination with substring like this:

$a = "0001 filename.txt"
Rename-Item -Path $a -NewName $("$($a.Substring(0,4)).txt") 
Martin
  • 1,853
  • 3
  • 15
  • 22
0

If you are always using the same convention like in your example, Digits and Non-Digits

You can use:

$Filename = Get-ChildItem 'C:\folder\0001 filename.txt'
Rename-Item $Filename -NewName ($Filename.Name -replace "\W+\w+[^.txt]")

If the convention is different you need to create a different regex

Avshalom
  • 8,657
  • 1
  • 25
  • 43
0

I'll throw mine in here as well. You can just use the .Split() method to break a string on spaces (or any character inside the parenthesis). We Split and then index into the values we want.

$a = "0001 filename.txt"
$a.Split()[1]
>filename.txt

If we wanted to do this to rename your file, it'd look like this.

Rename-Item $Filename -NewName $a.Split()[1]
FoxDeploy
  • 12,569
  • 2
  • 33
  • 48
0

Replace "E:\0000 File1.txt" with the path to your file. I assume you have a lot of files to do so here is the format for several files.

$File = "E:\File1.txt","E:\File2.txt","E:\File3.txt"

This is the full code. You can also give a directory full of files, but if that directory has sub-folders, they may be renamed by this. You should only have to change the first two lines to your liking.

$File = "E:\0000 File1.txt","E:\0000 File2.txt"
$CharsToKeep = 7

Get-ChildItem $File |
ForEach-Object{
    $Orig = $_.fullname
    $NewName = ($_.BaseName).Substring(0,$CharsToKeep) + $_.Extension
    Rename-Item -path $Orig -NewName $NewName
} # end Foreach. Also end Get-ChildItem