简体   繁体   English

使用PowerShell从.txt文件中使用字符串重命名多个文件

[英]Rename multiple files with string from .txt file using PowerShell

Im currently working on a programm that needs a .xml file, reads it into a Oracle Database and afterwards exports a new .xml file. 我目前正在开发需要.xml文件的程序,然后将其读入Oracle数据库,然后导出新的.xml文件。 But the problem is that the new file has to have the exact same name as the original file. 但是问题在于新文件必须具有与原始文件完全相同的名称。

I saved the original filenames into a .txt file and i'm now trying to search for a keyword inside the lines to rename the right files with the correct names inside the .txt file. 我将原始文件名保存到.txt文件中,现在我试图在行内搜索关键字,以使用.txt文件中的正确名称重命名正确的文件。 Here an example: 这里是一个例子:

My 4 files (exported from the Database): 我的4个文件(从数据库导出):

 PM.Data_information.xml
 PM.Data_location.xml
 PM.Cover_quality.xml
 PM.Cover_adress.xml

Content of Namefile.txt (original names): Namefile.txt的内容(原始名称):

 PM.Data_information_provide_SE-R-SO_V0220_657400509_3_210.xml
 PM.Data_location_provide_SE-R-SO_V0220_9191200509_3_209.xml
 PM.Cover_quality_provide_SE-R-SO_V0220_354123509_3_211.xml
 PM.Cover_adress_provide_SE-R-SO_V0220_521400509_3_212.xml

I only worked out how to get a line by selecting the linenumber: 我只想出了如何通过选择行号来获得一行:

$content = Get-Content C:\Namefile.txt
$informationanme = $content[0]
Rename-Item PM.Data_information.xml -NewName $informationname

Isn't there a way to select that line by searching for the keyword inside the string? 没有办法通过在字符串中搜索关键字来选择该行吗?

$content = Get-Content C:\temp\ps\NewFile.txt
$files = Get-ChildItem c:\temp\ps\ 

$content | 
    %{
        $currentLine = $_
        $file = $files | Where-Object { $currentLine.StartsWith($_.Name.Replace(".xml", "")) } 

        Rename-Item $file.Name $currentLine

    }

This code should do the trick. 这段代码可以解决问题。 Note you will need to have all of your files that need renaming in one folder. 请注意,您需要将所有需要重命名的文件放在一个文件夹中。 Set the folder path to the $files variable (currently set to c:\\temp\\ps ). 将文件夹路径设置为$files变量(当前设置为c:\\temp\\ps )。 Set the path where your NewFile.txt is to the $content path. NewFile.txt所在的路径设置为$content路径。

The code works by looping around each line in the NewFile.txt and finding any file where the name matches the start of the line (if there are any files that do not follow this pattern you will obviously need to update the code but hopefully gives you a good starting point). 该代码通过在NewFile.txt每一行周围循环并找到名称与该行开头匹配的任何文件来工作(如果有不符合此模式的文件,您显然需要更新代码,但希望可以为您提供)一个很好的起点)。

其他解决方案;)

  gci -Path "c:\temp" -File -Filter "*.xml" | % { rni $_.fullname (sls "C:\temp\Namefile.txt" -Pattern ([System.IO.Path]::GetFileNameWithoutExtension($_.fullname))).Line }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM