问题描述
有人可以帮忙使用 PowerShell
重命名文件夹中的单个 txt
文件吗,每个文件都需要根据每个 txt
文件中的关键字进行重命名。
例如
c:\temp\1.txt
可能有类似于 Invoice#: 4422 的行,因此需要将其重命名为 4422.txt
c:\temp\2.txt
可能有类似 Invoice#: 5454 这样的行,因此需要将其重命名为 5454.txt
等等..
我可以通过正则表达式获取发票号码
$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)
}
}