Removing part of files names and giving the name of one file type to another
The below piece of code should help you get through.
$sourceFolderPath = "D:\source"
Set-Location $sourceFolderPath
# 1 Replace the part of filename from underscore character with empty string
Get-ChildItem "*.rar", "*.pdf" | % { Rename-Item $_.Fullname -NewName (($_.BaseName -replace "_.*","") + $_.Extension) }
<# 2 ForEach 'rar' file object,
- Get the ID
- Get the corresponding 'pdf' by ID
- Rename the 'pdf' with BaseName of 'rar'
#>
Get-ChildItem "*.rar" | % {
$BaseName_rar = $_.BaseName
# If ID is just numbers
# Find the ID by replacing all non-digit characters in BaseName string of the 'rar' file with empty string
# This effectively returns the ID which are the only numbers expected in the filename
# $ID = $_.BaseName -replace "[^0-9]", ""
# UPDATE: If ID begins with a number and has a total length of 7
$ID = & {
$_.BaseName -match "(\d.{6})" | Out-Null
$matches[0]
}
Get-ChildItem "*$ID.pdf" | % { Rename-Item $_.FullName -NewName ($BaseName_rar + $_.Extension) }
}
UPDATE
Given that the ID begins with a digit and has a total length of 7, you can replace the $ID
assignment statement to the below
$ID = & {
$_.BaseName -match "(\d.{6})" | Out-Null
$matches[0]
}
Here's another approach that focuses on the delimiters in the text rather than length or character class. It assumes the underscore after the code is the first or only underscore in the filename.:
gci *.rar | ForEach{
$NewBase = $_.BaseName.Split('_')[0]
$Code = $NewBase.Split(' ')[-1]
Rename-Item $_.FullName "$NewBase.rar"
gci *.pdf | ? BaseName -match $Code | Rename-Item -NewName "$NewBase.pdf"
}
Step-by-step filename parsing demo:
PS C:\> $a = 'First Man 11e2345_some text to remove.rar'
PS C:\> $a.Split('_')
First Man 11e2345
some text to remove.rar
PS C:\> $a.Split('_')[0]
First Man 11e2345
PS C:\> $a.Split('_')[0].split(' ')
First
Man
11e2345
PS C:\> $a.Split('_')[0].split(' ')[-1]
11e2345
PS C:\>
References
Get-ChildItem/gci
ForEach-Object
String.Split Method
About Arrays
Rename-Item
Where-Object/?
PowerShell learning resources