bts86
asked on
Powershell Scripting help for sorting files into directories
I have an existing script that someone wrote for me that takes phone recording files from one location where all the files are dumped and sorts them into many sub directories. The information for sorting them is all within the file names.
They currently go by Extension\date\(Incoming or Outgoing)
The extension directories are growing quite large making it hard to find the day you are looking for.
I need to modify this to split the date into directories for year\month\day
So and incoming call today would end up like this ...\Ext-201\2017\10\30\inc oming\file name.mp3
Filenames are formatted like this:
20170516_041636PM_From-914 5555555_To -201_Ext-2 01.mp3 (this is an incoming call)
20170516_013713PM_From-201 _To-914555 5555_Ext-2 01.mp3 (this is an outgoing call)
Here is what I currently have:
Thanks in advance for any help.
They currently go by Extension\date\(Incoming or Outgoing)
The extension directories are growing quite large making it hard to find the day you are looking for.
I need to modify this to split the date into directories for year\month\day
So and incoming call today would end up like this ...\Ext-201\2017\10\30\inc
Filenames are formatted like this:
20170516_041636PM_From-914
20170516_013713PM_From-201
Here is what I currently have:
param ( [string]$p1 )
# Set source directory to Incoming FTP directory
$SourceFolder = "E:\FTP\$p1"
#Set target directory where the organized folders will be created
$TargetRoot = "E:\Recordings\$p1"
$Pattern = '(?<Date>\d{8})_(?:.*?)_From-(?<From>[^_]+)_To-(?<To>\d+)_Ext-(?<Ext>\d+)'
Get-Childitem -Path $SourceFolder -Filter *.mp3 | ForEach-Object {
Write-Host "Processing '$($_.Name)'" -NoNewline
If ($_.BaseName -match $Pattern) {
$CallType = If ($Matches['From'] -eq $Matches['Ext']) {'Outgoing'} Else {'Incoming'}
$TargetFolder = "$($TargetRoot)\Ext-$($Matches['Ext'])\$($Matches['Date'])\$($CallType)"
Write-Host " --> '$($TargetFolder)'"
If (-not (Test-Path -Path $TargetFolder)) {
New-Item -Path $TargetFolder -ItemType Directory | Out-Null
}
Move-Item -Path $_.FullName -Destination $TargetFolder
} Else {
Write-Host ""
Write-Warning -Message "File '$($_.Name)' does not match the expected pattern."
}
}
Thanks in advance for any help.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks, this works. I just had to make a minor edit on line 15:
$Day = $($Matches['Date']).Substr ing(6,2)
$Day = $($Matches['Date']).Substr
Purpose of this different pattern is to parse the date, replacing the substring operations. Also, replacing the If statement with an index based on the $From -eq $Ext comparson. Also, all variables are assigned in a single statement.
Open in new window