社内SEの話

日々起きたことの記録用

[Powershell] Rename the file name to a serial number

↓プログラミングで副業を考えたらこちら↓

Recently, there are many opportunities to handle a large amount of photos and process OCR.

Even if it is in the acquired state, it is difficult to debug without renaming.

You can rename it with Python etc., but Powershell is overwhelmingly easier, so let Powershell handle the renaming.

Program

Step1

Move to the folder specified in

Step2

Start Powershell console

$i=0

Get-ChildItem -File | sort LastWriteTime | % { Rename-Item $.Name ("{0:000}{1}" -f $i++, $.Extension) }

If current renaming a folder other than a directory

Use Get-ChildItem -File -Path ****

when

Description

1) Get-ChildItem: File acquisition

-File only extracts files. If you want to remove the folder, remove -File.

By the way, the ls command is an alias for Get-ChildItem, so ls will give the same result.

learn.microsoft.com

2) Sort in the order you want to be serial.

This time, the files are sorted in ascending order of time when they were written.

Items that can be sorted are items that can be obtained with Get-ChildItem.

3) %{} is the syntax to receive the value obtained from the pipeline

4) Rename-Item $.Name ("{0:000}{1}" -f $i++, $.Extension): Rename the file in turn.

Rename-Item

learn.microsoft.com

Rename-Item File before change File after change

$_.Name pipe Filename taken from line

"{0:000}" -f $i++: Returns the result of zero padding the number using the format function.

$_.Extension holds the extension. and return the result to {1}.

The first argument is a serial number and the second argument is the extension format.

If you want to add a specified string before the serial number, use "Test_{0:000}".