重命名文件夹以匹配文件名

时间:2016-04-06 22:50:50

标签: powershell

我有一堆文件夹需要更改,如下所示:

之前:

  • FolderNamedX(2016)
    • fileNamedY.png

后:

  • NamedSameAsFileWithin(2016)

    • fileNamedY.png

基本上,文件夹名称需要更改以匹配其中的文件名,并同时保留年份。

我正在尝试使用PowerShell执行此操作。 任何善良的灵魂都可以引导我朝着正确的方向前进?

我是PowerShell的新手,到目前为止我有类似的东西(不要笑得太厉害):

Get-ChildItem -Path "C:\Lab" | ForEach-Object -Process {
    $Filename = Filename.Trim(".png") # Not sure how to retrieve the filename from current folder
    $OldFolderName = $_.Name
    $NewFolderNameLeft, $NewFolderNameRight = $OldFolderName.Split("(")
    $NewFolderNameLeft = $Filename
    Rename-item -Path $_.Name -NewName ($NewFolderNameLeft+"("+$NewFolderNameRight) -WhatIf
}

2 个答案:

答案 0 :(得分:2)

还没有机会测试,但这应该有效。离开-whatif并且您已经拥有了要测试的环境。

Get-ChildItem -Path "C:\Lab" | Where-Object{$_.PSisContainer} | ForEach-Object -Process {
    # Get the filename without the extension
    $pngName = Get-ChildItem $_ -Filter "*.png" | Select-Object -ExpandProperty BaseName
    Rename-Item -Path $_.FullName -NewName ($_.Name -replace ".*\(","$pngName (") -WhatIf
}

获取路径下的每个文件夹。然后,对于每个文件夹,返回PNG的基本名称。用它来替换第一个打开括号之前的所有内容。一个非常简单的正则表达式确保了这一点。如果有没有png的文件夹可能会很糟糕,所以你需要小心,并可能建立一些逻辑来解决这个问题。

答案 1 :(得分:1)

# Process all the subdirectories in d:\test
# (ignore any files)
Get-ChildItem -Directory "d:\test\" | ForEach {

    # Get the .png files in each directory; get the first file 
    # (so it doesn't break if there's more than one)
    $fileName = Get-ChildItem $_ -File -Name *.png | Select -First 1

    # Rename the directory with a regular expression pattern
    # which puts in the file's BaseName (name with no extension).
    #
    # The regular expression matches anything up to the first " ("
    # i.e. everything before " (2016)" gets replaced, but that is kept.
    #
    Rename-Item $_ -NewName ($_.Name -replace '.*(?= \()', $fileName.BaseName)

}

只是经过轻微测试。