i have a bunch of files on a ftp server. there named with different naming patterns
heres a couple
2014-06-09_1324_8328924511_16749732.wav
2065787459 by mkane@somecompany.com @ 1_17_36 PM.wav
20140609-093628_9044721215_DSA11909-all.mp3
they all share a 10 digit phone # eg. 8328924511
I need to extract just the phone # and rename the file just the phone# that was extracted
im stuck because there are all different patterns excluding the 10 digits
any help would be greatly appreciated
im using this for the 10 digits = ‘\d{10}’
Hi H.
You could try something like this:
Get-ChildItem -Path $sourcedir |
foreach {
if ($_ -match "(\d{10})" ) {
Rename-Item -Path $_.FullName -newName "$($matches[0])$($_.Extension)"
}
}
It’s not pretty, but it works
any way of adding the date to the name too?
its working on 95% but im a couple im getting this error
Rename-Item : Cannot create a file when that file already exists.
At line:7 char:13
Then you might want to add a small test to check if the file already exists.
If it does a new uniquie name needs to be hammered by adding something to the name.
It could be any random number.
now this
Rename-Item : Cannot rename because the target specified represents a path or
device name.
The thing is you need to handle several scenarios here. One is the first time you identify a file based on name. The next time the script is executed it will find the same files once more.
I would proberbly add a prefix to the files that have been renamed and filter theese out the next time the script ran.
Then you need to ensure all files are renamed using a unique name. For this you could use a simple counter in a loop to create a suffix and add it to the filename
The following snippet kinda works in my test environment. For all files the script touches it will add a prefix ‘renamed-’ and will also skip any files that have a prefix of ‘renamed’
function Get-UniqueFileName {
[cmdLetBinding()]
Param(
[Parameter(Mandatory=$true)]
[ValidateScript({Test-Path $_})]
[String]$Path,
[Parameter(Mandatory=$true)]
[ValidateNotnullOrEmpty()]
[String]$BaseName,
[ValidateNotnullOrEmpty()]
[String]$Suffix = 'renamed',
[Parameter(Mandatory=$true)]
[ValidateNotnullOrEmpty()]
[String]$Extention
)
$base = "$path/$suffix-$BaseName"
$newPath = "$base$Extention"
while (Test-Path $newPath) {
$counter++
$newPath = Join-Path -Path $path -ChildPath "$suffix-$BaseName-$counter$Extention"
Write-Verbose $newPath
}
write $newPath
}
$sourcedir = 'D:\test'
Get-ChildItem -Path $sourcedir |
foreach {
if ($_ -match "(\d{10})" ) {
if ($_ -notmatch "^renamed" ) {
write $_
Rename-Item -Path $_.FullName -newName (Get-UniqueFileName -Path $sourcedir -BaseName $matches[0] -Extention $_.Extension -Verbose )
}
}
}
thank you Stein you have been a tremendous help!