Using Powershell to recursively rename directories using a lookup file

让人想犯罪 __ 提交于 2019-12-24 12:12:36

问题


I need to rename a lot of directories and their sub directories.

I have a csv file which contains the old directory names and the required new name.

1,blah,old_name1,new_name2,wibble
2,foo,old_name2,new_name2,bar
3,john,old_name3,new_name3,paul
4,george,old_name4,new_name4,ringo

Note that some of the directory names are

old_name1-morestuffhere 

which need to be renamed to

 new_name1-morestuffhere

I know broadly how I'd do this in bash:

mv -r `cat file.csv | awk -F, '{print $3* $4*}'`

..but I'm bound to and totally lost with powershell.

EDIT: Here's what I've got so far. Is this close?:

cat .\file.csv | foreach { $oldname = $_.split(",")[2], $newname = $_.split(",")[3], move-item $oldname*, $newname*}

回答1:


The "-morestuffhere" is the tricky part. The Path parameters (ie source location) on Move-Item and Rename-Item don't take wildcards. But that can be solved another way. First, can you add a CSV header to your CSV file like this:

Index,F2,OldName,NewName,F5
1,blah,old_name1,new_name2,wibble
...

If so, we can use PowerShell's Import-Csv cmdlet. Now the following seems kind of complicated but it handles the case of multiple OldName-<differentstuffhere> to NewName-<sameasoldnamestuffhere> renames.

$names = Import-Csv names.csv | 
             Foreach {
                 $oldDirs=@(Get-ChildItem . -r -filter "$($_.OldName)*" | 
                            ?{$_.PSIsContainer} | %{$_.FullName})
                 Add-Member -in $_ NoteProperty OldDirs $oldDirs -PassThru
             }

foreach ($name in $names) {
    foreach ($oldDir in $name.oldDirs) {
        $dir     = Split-Path $oldDir -Parent
        $suffix  = (Split-Path $oldDir -Leaf).Substring($name.OldName.Length)
        $newPath = Join-Path $dir ($name.NewName + $suffix)
        Rename-Item $oldDir ($name.NewName + $suffix) -WhatIf -ea 0
    }
}

This is hand intrepreted so there may be errors. Remove the -Whatif when you're satisfied with the results.




回答2:


this is an alternative, since you should have vbscript already installed

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile= "C:\test\file.csv"
Set objFile = objFS.OpenTextFile(strFile,1)
Do Until objFile.AtEndOfStream 
    strLine = objFile.ReadLine
    s = Split(strLine,",")
    oldname = s(2)
    newname = s(3)
    WScript.Echo oldname, newname
    Set objFile=objFS.GetFile(oldname)
    objFile.Name = newname  
    Set objFile=Nothing 
Loop


来源:https://stackoverflow.com/questions/1686443/using-powershell-to-recursively-rename-directories-using-a-lookup-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!