Search This Blog

2013-03-01

PowerShell: Rename Directory To File Name

Product: PowerShell

This command will generate a script which can be used to rename a directory to txt file residing inside the parent directory. This used the full path name

I have a directory which contains 1 txt file used to label the purpose of the directory.

G:\Recovered\recup_dir.1\fat32\007785\Argon_000.txt

G:\Recovered\recup_dir.1\fat32\0217CE\Superman_000.txt

get-childitem -recurse -filter *.txt | %{Write-Host Rename-Item $_.directory $_.basename }

Rename-Item G:\Recovered\recup_dir.1\fat32\007785 Argon_000
Rename-Item G:\Recovered\recup_dir.1\fat32\0217CE Superman_000
Rename-Item G:\Recovered\recup_dir.1\fat32\02B84B Anony_000
Rename-Item G:\Recovered\recup_dir.1\fat32\031CD8 IronMan_000
Rename-Item G:\Recovered\recup_dir.1\fat32\038977 Goats_000

This is a similar command, but will use relative name of the directory


get-childitem -recurse -filter *.txt | %{Write-Host Rename-Item $_.directory.basename $_.basename }

Rename-Item 007785 Argon_000
Rename-Item 0217CE Superman_000
Rename-Item 02B84B Anony_000
Rename-Item 031CD8 IronMan_000
Rename-Item 038977 Goats_000
It is nice to save this into a batch file for audit as well as historical troubleshooting purpose

Following command is similar to 2nd command, but it will execute immediately instead of displaying only

get-childitem -recurse -filter *.txt | %{ rename-item -path $_.directory -NewName $_.basename -verbose }

While finding out the correct syntax to dynamically rename the directory, I used follwoing


Get-ChildItem -recurse -include *.txt | select-object -property directory, basename


Directory                                                   BaseName
---------                                                   --------
G:\Recovered\recup_dir.1\fat32\[007785]                     Argon_000
G:\Recovered\recup_dir.1\fat32\[00CB99]                     Superman_000
G:\Recovered\recup_dir.1\fat32\[01A7E1]                     Anony_000
G:\Recovered\recup_dir.1\fat32\[0217CE]                     IronMan_000
G:\Recovered\recup_dir.1\fat32\[02B84B]                     Goats_000

Other commands used

PS G:\Recovered\recup_dir.1> Get-ChildItem -recurse -include *.txt | get-member
PS G:\Recovered\recup_dir.1\fat32> Get-ChildItem -recurse -include *.txt | select-object directory, name

No comments:

Blog Archive