根据文件内容重命名文件夹中的所有txt文件

马夏洛特

有人可以帮忙PowerShell重命名txt文件夹中的单个文件,每个文件都需要根据每个文件中的关键字进行重命名txt

例如

c:\temp\1.txt可能有像Invoice#: 4422这样的行,因此需要将其重命名为4422.txt

c:\temp\2.txt可能有像Invoice#: 5454这样的行,因此需要将其重命名为5454.txt

等等..

我可以通过 Regex 获取发票编号

$filecontents -match "INVOICE\#: (\d+):"

* C:\temp*文件夹包含大量txt不同发票编号文件,PS 脚本需要重命名所有文件。谢谢,

圣地亚哥·斯夸松

试试这个,如果它有效,请删除-WhatIf开关Rename-Item

$files = Get-ChildItem "c:\temp\*.txt"
$index = [collections.generic.list[string]]::new()

foreach($file in $files)
{
    if((Get-Content $file -Raw) -match '(?<=Invoice#:\s)\d+')
    {
        $invoiceNumber = $matches[0]
        
        if($index.contains($invoiceNumber))
        {
            Write-Warning "File with name $invoiceNumber.txt already exists. Skipping."
            continue
        }

        "Renaming {0} to $invoiceNumber.txt" -f $file.Name
        $file | Rename-Item -NewName $invoiceNumber.txt -WhatIf
        $index.Add($invoiceNumber)
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章