Rename the first 20 characters of each file name in the file

I am trying to write a script in powershell to remove the first 20 characters of each MP3 file name in a folder, I created a test.ps file and inserted powershell code 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.

+4
source share
3 answers

It can make you start. (There are probably much more concise ways, but it works and is read when you need to support it later. :-))

I created the folder C:\TempFiles and created the following files in this folder:

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

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

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

from the actual command line.)

Then I opened PowerShell ISE in the Start menu and ran this script. It creates an array ( $files ) containing only the file names, 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 a folder containing:

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

To run the script from the command line, you need to change some default Windows security settings. You can find out about them using the PowerShell ISE help file (from the menu) and searching about_scripts or by running help about_scripts from the ISE prompt. See the How To Run A Script subsection in the help file (it is much easier to read).

+6
source

Your code really works. Two things...

  • Rename the file to test.ps1 .
  • Launch it in the folder where the MP3 files are located. Since you did not specify a path to Get-ChildItem , it will be launched in the current directory.

I tested your line by creating a bunch of mp3 files like this -

 1..30 | % { new-item -itemtype file -Name ( $_.ToString().PadLeft(30, 'A') + ".mp3" )} 
+2
source

I would use a more “safe” way (you get an error if the file name is shorter than the length in question, you also target the file extension as part of the common characters). Check if the base name of each file is more than 21 characters (if you delete the first 20, it may still have a name with one character). It may fail if the directory contains a file with the same name after removing the first 20, you can develop it further yourself):

 gci *.mp3 | foreach{ if($_.BaseName.Length -ge 21) { $ext = $_.Extension $BaseName = $_.BaseName.Substring(20) Rename-Item $_ -NewName "$BaseName$ext" } } 
0
source

Source: https://habr.com/ru/post/1414473/


All Articles