Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename first 20 characters of every filename in a file

I am trying to write a script in powershell to remove the first 20 characters of every MP3 filename in a folder, I have created a file 'test.ps' and inserted the powershell code below into it,

gci *.mp3 | rename-item -newname { [string]($_.name).substring(20) }

When I run this file in powershell.exe nothing happens,

Can anyone help? Thanks.

like image 327
rusty009 Avatar asked Feb 21 '23 08:02

rusty009


1 Answers

This may get you started. (There are probably much more concise ways, but this works and is readable when you need to maintain it later. :-) )

I created a folder C:\TempFiles, and created the following files in that folder:

TestFile1.txt
TestFile2.txt
TestFile3.txt
TestFile4.txt

(I created them the old-fashioned way, I'm afraid. <g>. I used

for /l %i in (1,1,4) do echo "Testing" > TestFile%i.txt

from an actual command prompt.)

I then opened PowerShell ISE from the start menu, and ran this script. It creates an array ($files), containing only the names of the files, and processes each of them:

cd \TempFiles
$files = gci -name *.txt
foreach ($file in $files) {
  $thename = $file.substring(4);
  rename-item -path c:\TempFiles\$file -newname $thename
}

This left the folder containing:

File1.Txt
File2.Txt
File3.Txt
File4.Txt
File5.Txt

In order to run a script from the command line, you need to change some default Windows security settings. You can find out about them by using PowerShell ISE's help file (from the menu) and searching for about_scripts or by executing help about_scripts from the ISE prompt. See the sub-section How To Run A Script in the help file (it's much easier to read).

like image 140
Ken White Avatar answered Mar 04 '23 07:03

Ken White