Search This Blog


PowerShell: Rename File Name To Directory Name

Product: PowerShell

This command will generate a script which can be used to rename multiple files in the directory to the directory name.  This is used when:

1. Inconsistent filename in the directory, each with unique extension
2. Directory name is unique, but filename is random, so you would like to make the filename to be same as directory name

I have a directory which contains following file extensions used for the purpose of this post:

Dir: 4Ever
Files: file1.trp, file1.txt, file1.idx, file1.nfo

get-childitem  Stockings | rename-item  -NewName { $ + $_.extension }

PS I:\SVHD_VIDEO> dir 4Ever

    Directory: I:\SVHD_VIDEO\4Ever

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        11/13/2016   9:20 AM 1020313600 4Ever.trp
-a---        11/13/2016   9:20 AM     857792 4Ever.idx
-a---        11/13/2016   9:20 AM       4228 4Ever.ifo
-a---        11/13/2016   9:20 AM       1480 4Ever.txt

For renaming across multiple directories, use following syntax

get-childitem  -recurse | where { ! $_.PSIsContainer } | rename-item  -NewName { $ + $_.extension }

where PSIsContainer means it is a directory.  Exclamation mark (!) used to exclude directory

No comments: