2017-10-12 56 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 
相關問題