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"
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"
You could use a combination with substring like this:
$a = "0001 filename.txt"
Rename-Item -Path $a -NewName $("$($a.Substring(0,4)).txt")
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
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]
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