[英]Rename all txt files in a folder based on file content
Can someone please help to use PowerShell
to rename individual txt
files in a folder, each file needs to be renamed based on a keyword inside each individual txt
file.有人可以帮忙使用
PowerShell
重命名文件夹中的单个txt
文件,每个文件需要根据每个单独的txt
文件中的关键字重命名。
eg例如
c:\temp\1.txt
may have a line like Invoice#: 4422 so it needs to be renamed as 4422.txt
c:\temp\1.txt
可能有类似Invoice#: 4422这样的行,因此需要将其重命名为4422.txt
c:\temp\2.txt
may have a line like Invoice#: 5454 so it needs to be renamed as 5454.txt
c:\temp\2.txt
可能有类似Invoice#: 5454这样的行,因此需要将其重命名为5454.txt
and so on..等等..
I am able to get the invoice number by Regex as我可以通过正则表达式获取发票编号
$filecontents -match "INVOICE\#: (\d+):"
The * C:\temp* folder contains a big number of txt
files with different invoice numbers and PS script needs to rename all files. * C:\temp*文件夹包含大量具有不同发票编号的
txt
文件,PS 脚本需要重命名所有文件。 Thanks,谢谢,
Try this, if it works remove the -WhatIf
switch on Rename-Item
:试试这个,如果它有效,请移除
Rename-Item
上的-WhatIf
开关:
$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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.