求编写PowerShell脚本:批量匹配Excel生成指定命名TXT文件
PowerShell脚本实现方案及逻辑说明
直接可用脚本(推荐,需安装模块)
先执行以下命令安装依赖模块(仅需一次):
Install-Module -Name ImportExcel -Scope CurrentUser -Force
替换路径后运行脚本:
# 替换为你的目标文件夹路径 $targetFolder = "C:\Your\Target\Folder" # 替换为你的Excel文件路径 $excelPath = "C:\Your\Target\Folder\data.xlsx" # 读取Excel数据,将B列作为键、A列作为值存入哈希表(快速匹配用) $excelMap = @{} Import-Excel -Path $excelPath | ForEach-Object { $excelMap[$_.B] = $_.A } # 遍历文件夹内所有文件 Get-ChildItem -Path $targetFolder -File | ForEach-Object { # 获取不带扩展名的文件名 $fileNameWithoutExt = $_.BaseName # 检查是否有匹配的Excel数据 if ($excelMap.ContainsKey($fileNameWithoutExt)) { # 生成新TXT文件名 $newTxtName = "$fileNameWithoutExt-$($excelMap[$fileNameWithoutExt]).txt" $newTxtPath = Join-Path -Path $targetFolder -ChildPath $newTxtName # 创建空TXT文件(已存在则跳过,需覆盖加-Force参数) New-Item -Path $newTxtPath -ItemType File -ErrorAction SilentlyContinue Write-Host "已创建文件: $newTxtName" } }
无模块依赖替代方案(适用于无法安装模块的场景)
需系统已安装Excel,脚本逻辑如下:
$targetFolder = "C:\Your\Target\Folder" $excelPath = "C:\Your\Target\Folder\data.xlsx" $excelMap = @{} # 初始化Excel COM对象 $excel = New-Object -ComObject Excel.Application $excel.Visible = $false $workbook = $excel.Workbooks.Open($excelPath) $worksheet = $workbook.Worksheets.Item(1) # 获取B列最后一行行号 $lastRow = $worksheet.Cells($worksheet.Rows.Count, 2).End(-4162).Row # 遍历Excel行(假设第1行是表头,从第2行开始读取) for ($i=2; $i -le $lastRow; $i++) { $bColumnValue = $worksheet.Cells.Item($i, 2).Text $aColumnValue = $worksheet.Cells.Item($i, 1).Text $excelMap[$bColumnValue] = $aColumnValue } # 释放Excel COM对象,避免进程残留 $workbook.Close() $excel.Quit() [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet) | Out-Null [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() # 后续文件遍历与生成逻辑和上方一致 Get-ChildItem -Path $targetFolder -File | ForEach-Object { $fileNameWithoutExt = $_.BaseName if ($excelMap.ContainsKey($fileNameWithoutExt)) { $newTxtName = "$fileNameWithoutExt-$($excelMap[$fileNameWithoutExt]).txt" $newTxtPath = Join-Path -Path $targetFolder -ChildPath $newTxtName New-Item -Path $newTxtPath -ItemType File -ErrorAction SilentlyContinue Write-Host "已创建文件: $newTxtName" } }
实现逻辑拆解
- 高效数据索引构建:把Excel的A、B列转成哈希表,用B列的文件名做键、A列的关联文本做值。哈希表的查找速度是O(1),比逐行遍历Excel匹配快得多,文件数量多的时候优势明显。
- 精准文件遍历:用
Get-ChildItem -File只处理文件夹内的文件,自动跳过子文件夹。直接调用BaseName属性获取不带扩展名的文件名,省去手动截取字符串的麻烦,也避免了复杂扩展名的处理错误。 - 匹配与文件生成:对每个文件的无扩展名名称,检查哈希表中是否存在对应键。如果匹配成功,按指定格式拼接新文件名,用
New-Item创建空TXT文件。默认跳过已存在的文件,需要覆盖的话给New-Item加-Force参数即可。
内容的提问来源于stack exchange,提问作者pwsh2succeed
相关产品推荐
相关产品推荐

