在PowerShell中重命名多个文件名有时不起作用

问题描述

我问了一个问题,我在哪里尝试使用PowerShell从多个文件夹中的多个文件名称删除部分。可能需要删除的部分是“-xx_xx”“-yy_yy”“-zz_zz”等。

为此,我正在使用:

Get-Childitem -Recurse | Rename-Item -NewName { $_.Name -replace " - xx_xx","" -replace " - yy_yy","" -replace " - zz_zz",""}

效果很好。

但是,我收到一条说明,即对于特定项目,命名约定将发生变化。对于类似“ -xx_xx-yy_yy-A-B”或“ -xx_xx_zz_zz_zz-A-B”或“ -xx_xx_yz_yz-A-B”之类的东西,请注意,没有空格。我以为我可以简单地将它分解成小块,这样就可以了,就像这样:

Get-Childitem -Recurse | Rename-Item -NewName { $.Name -replace "-xx_xx-yy_yy-A-B","" -replace "-xx_xx_zz_zz-A-B","" -replace "-xx_xx_yz_yz-A-B","" }

但是...不起作用。我以为它可能与连字符有关,但是除非我以某种方式不正确地将它们转义了,否则都不会起作用。

这是我收到的错误消息:

Rename-Item : The input to the script block for parameter 'NewName' Failed. The term '$.Name' is not recognized as the name of a cmdlet,function,script file,or operable program. Check the spelling of the name,or if a path was included,verify that the path is correct and try again.
At line:1 char:47
+ ... em -NewName { $.Name -replace "-xx_xx-yy_yy-A-B","" -replace "-xx_xx- ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (True Dialog Requests-xx_xx-yy_yy-A-B.htm:PSObject) [Rename-Item],Para
   meterBindingException
    + FullyQualifiedErrorId : ScriptBlockArgumentInvocationFailed,Microsoft.PowerShell.Commands.Renameitemcommand
  1. 如何使它工作
  2. 为什么它不能与“-xx_xx”等一起使用?
  3. 有没有更好的方法来做到这两个?

解决方法

您需要使用$_.Name

Get-Childitem -Recurse | Rename-Item -NewName { $_.Name -replace "-xx_xx-yy_yy-A-B","" -replace "-xx_xx_zz_zz-A-B","" -replace "-xx_xx_yz_yz-A-B","" }
,

我当前正在使用VBA来完成此任务。 使用它之前,必须从参考安装:
Microsoft脚本运行时

A列中是文件夹内部的现有名称。
在D列中,它们应该有什么名字。

Sub RenameMultipleFiles()
With Application.FileDialog(msoFileDialogFolderPicker)
    .AllowMultiSelect = False
    If .Show = -1 Then
        selectDirectory = .SelectedItems(1)
        dFileList = Dir(selectDirectory & Application.PathSeparator & "*")
    
        Do Until dFileList = ""
            curRow = 0
            On Error Resume Next
            curRow = Application.Match(dFileList,Range("A:A"),0)
            If curRow > 0 Then
                Name selectDirectory & Application.PathSeparator & dFileList As _
                selectDirectory & Application.PathSeparator & Cells(curRow,"D").Value
            End If
    
            dFileList = Dir
        Loop
    End If
End With
End Sub

如果您在A列中没有现有文件名的列表,则以下是如何收集它们的示例:

Option Explicit
Sub ListAllFiles()
Dim objFSO As Scripting.FileSystemObject
Dim objFolder As Scripting.Folder
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("Your Path")
Call getFilesDetails(objFolder)

End Sub

Function getFilesDetails(objFolder As Scripting.Folder)
Dim objFile As Scripting.File
Dim nextRow As Long
nextRow = Cells(Rows.count,1).End(xlUp).Row + 1
For Each objFile In objFolder.Files
   Cells(nextRow,1) = objFile.Name
   nextRow = nextRow + 1
Next
End Function