对不起以前的困惑......
今天我花了几个小时尝试编写一个PowerShell脚本,该脚本将从系统#1中删除客户端ID(例如,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
}
它不接受" NewName"因为它声明它是一个空字符串。我跑了:
Get-Variable | select name,value,Description
新名称显示为名称但没有任何价值。如何将正则表达式的输出传递给重命名?
答案 0 :(得分: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
答案 1 :(得分:0)
我最终使用了一个名为" Bulk Rename Utility"和Excel。我可以通过BRU运行各种重命名正则表达式,并在一些Excel格式化后添加引用.txt文件。