We help IT Professionals succeed at work.
Get Started

Powershell Scripting help for sorting files into directories

bts86 asked
Last Modified: 2018-07-18
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\incoming\filename.mp3

Filenames are formatted like this:
20170516_041636PM_From-9145555555_To-201_Ext-201.mp3 (this is an incoming call)
20170516_013713PM_From-201_To-9145555555_Ext-201.mp3 (this is an outgoing call)

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."

Open in new window

Thanks in advance for any help.
Watch Question
System Architect
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE