【问题标题】:Remove Sections of File Names w/PowerShell使用 /PowerShell 删除文件名部分
【发布时间】:2023-04-01 02:05:01
【问题描述】:

在编码方面我不是很了解,但我正在尝试使用 PowerShell 找到一种方法来从多个文件中删除前 X 个字符和最后 X 个字符。因此,只保留中间部分。

例如) INV~1105619~43458304~~1913216023~0444857,其中1913216023是发票号。之前和之后的所有内容都需要从文件名中删除。

我用过: 获取子项 *.pdf | rename-item -newname { string.substring(22) } 删除前 22 个字符,但无法创建代码来删除剩余的一半。所有文件的字符数相同,但发票号前后的数字不同(每个文件名不同)。

非常感谢任何帮助/建议!

【问题讨论】:

  • 我想这就是你想要的:if ("INV~1105619~43458304~~1913216023~0444857".substring(22) -match "^([^\~]*)") { $Matches.1 }
  • 发票号码是否总是相同的数字长度?
  • 是的。这些发票的长度始终为 10 位数。我正在尝试重命名一堆具有相同结构的文件。 (22 个字符~~INVOICE#~~8 个字符)
  • ("INV~1105619~43458304~~1913216023~0444857" -split "~")[-2]

标签: powershell file rename


【解决方案1】:

有几种方法可以做到这一点。
如果您确定不会遇到命名冲突(因此所有文件都有不同的发票编号),以下是三个额外选项的方法:

(Get-ChildItem -Path 'D:\Test' -Filter '*~~*~*.pdf' -File) | 
    Rename-Item -NewName { 
        # my favorite method
        '{0}{1}' -f ($_.BaseName -split '~')[-2], $_.Extension

        # or
        # '{0}{1}' -f ($_.BaseName -replace '^.*~~(\d{10})~.+$', '$1'), $_.Extension

        # or this one
        # '{0}{1}' -f ([regex]'~~(\d+)~').Match($_.BaseName).Groups[1].Value, $_.Extension

        # or if you are absolutely sure of the position and length of the invoice number
        # '{0}{1}' -f $_.BaseName.Substring(22,10), $_.Extension
    }

Get-ChildItem 行位于括号之间,以确保在继续之前完成 FileInfo 对象的收集。如果您不这样做,您可能会尝试多次重命名项目

【讨论】:

    【解决方案2】:

    假设目标子字符串始终具有相同的长度,则 substring() 有一个具有长度参数的重载。

    'INV~1105619~43458304~~1913216023~0444857'.substring
    
    OverloadDefinitions
    -------------------
    string Substring(int startIndex)
    string Substring(int startIndex, int length)
    
    
    $startIndex, $length = 22, 10
    'INV~1105619~43458304~~1913216023~0444857'.substring($startIndex, $length)
    
    1913216023
    
    
    dir ('?'*40) | rename-item -newname { $_.name.substring(22,10) } -whatif
    
    What if: Performing the operation "Rename File" on target 
          "Item: C:\users\admin\foo\INV~1105619~43458304~~1913216023~0444857 
    Destination: C:\users\admin\foo\1913216023".
    

    【讨论】:

      猜你喜欢
      • 2017-04-08
      • 1970-01-01
      • 2018-06-19
      • 2020-02-11
      • 2012-01-11
      • 1970-01-01
      • 2015-06-20
      • 2022-11-17
      • 2017-09-16
      相关资源
      最近更新 更多