2017-10-12 57 views
-3

对不起,以前的混乱......在PowerShell中重命名文件与参考文件

我已经花了几个小时今天想写一个PowerShell脚本,将拉一个客户端ID掀起了PDF从系统#1(例如,Smith,John_H123_20171012.pdf,其中客户端ID是H #### value),然后在包含系统1和系统2中的客户端ID的Excel电子表格中查找它,然后将该文件重命名为所需的格式用于系统2(xxx_0000000123_yyy.pdf)。

一个问题是客户端#在系统2中是2-4位数,并且总是以0为前缀。

使用Powershell和正则表达式。

这是我想用我的最初命名的第一部分:

Get-ChildItem -Filter *.pdf | Foreach-Object{ 
     $pattern = "_H(.*?)_2" 
     $OrionID = [regex]::Match($file, $pattern).Groups[1].value 
     Rename-Item -NewName $OrionID 
    } 

它不接受“新名称”,因为它指出它是一个空字符串。我已运行:

Get-Variable | select name,value,Description 

新名称显示为名称,但没有值。我如何将正则表达式的输出传递给重命名?

+0

如果您可以将excel另存为csv,那么在powershell中处理csv会更容易 – Jimbo

+0

不幸的是,stackoverflow不是免费的代码生成服务。您需要首先努力解决问题,而不是要求其他人为您编写代码。 –

+0

$ files = Get-ChildItem -Path C:\ PowerShell \ Test foreach($ file in $ files) { $ pattern =“_H(。*?)_2” $ OrionID = [regex] :: Match( $文件,$模式).Groups [1] .value #$ _ -replace“(。*)(\。pdf)”,$ OrionID 写主机$ OrionID Rename-Item -Path $ _。FullName - NewName $ OrionID } – Finny

回答

0

我最终使用了一个名为“批量重命名实用程序”和Excel的实用程序。我可以通过BRU运行各种重命名正则表达式,并在某些Excel格式化后添加引用.txt文件。

0

在调试器中逐行运行此代码,您将了解其工作原理。

#Starts an Excel process, you can see Excel.exe as background process 
$processExcel = New-Object -com Excel.Application 
#If you set it to $False you wont see whats going on on Excel App 
$processExcel.visible = $True 

$filePath="C:\somePath\file.xls" 
#Open $filePath file 
$Workbook=$processExcel.Workbooks.Open($filePath) 

#Select sheet 1 
$sheet = $Workbook.Worksheets.Item(1) 
#Select sheet with name "Name of some sheet" 
$sheetTwo = $Workbook.Worksheets.Item("Name of some sheet") 

#This will store C1 text on the variable 
$cellString = $sheet.cells.item(3,1).text 
#This will set A4 with variable value 
$sheet.cells.item(1,4) = $cellString 

#Iterate through all the sheet 
$lastUsedRow = $sheet.UsedRange.Rows.count 
$LastUsedColumn = $sheet.UsedRange.Columns.count 
for ($i = 1;$i -le $lastUsedRow; $i++){ 
    for ($j = 1;$j -le $LastUsedColumn; $j++){ 
     $otherString = $sheet.cells.item($i,$j).text 
    } 
} 

#Create new Workbook and add sheet to it 
$newWorkBook = $processExcel.Workbooks.Add() 
$newWorkBook.worksheets.add() 
$newSheet = $newWorkBook.worksheets.item(1) 
$newSheet.name="SomeName" 

#Close the workbook, if you set $False it wont save any changes, same as close without save 
$Workbook.close($True) 
#$Workbook.SaveAs("C:\newPath\newFile.xls",56) #You can save as the sheet, 56 is format code, check it o internet 
$newWorkBook.close($False) 

#Closes Excel app 
$processExcel.Quit() 

#This code is to remove the Excel process from the OS, this does not always work. 
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($processExcel) 
Remove-Variable processExcel 
相关问题