Here is a little function to create a new folder structure from a bunch of files.
The folder structure looks like this:
E:\Archives\LatestArchiveFiles
Log20100821.log
Archive20100821.log
Routine20100821.log
Log20100828.log
Archive20100828.log
Routine20100828.log
After running the function the folder structure looks like this:
E:\Archives\LatestArchiveFiles
20100821
Log20100821.log
Archive20100821.log
Routine20100821.log
20100828
Log20100828.log
Archive20100828.log
Routine20100828.log
It works by doing a Get-ChildItem on the folder and grouping the files by the date part of the file name, then it creates new folders based on the group name and moves the relevant files in to the new folder.
Function Create-New-Folder-Structure{
param($path = 'E:\Archives\LatestArchiveFiles')
$VerbosePreference = "Continue"
$ArchivePath = $null
Set-Location $path
$GroupByDate = {$z =($_.name).ToString(); $z.Substring($z.Length – 12, 8)}
$archiveGroups = Get-ChildItem '*.log' | Group-Object $GroupByDate | select group,name
write-verbose "The current folder is $pwd"
write-verbose "Start of Date Group Processing`n"
foreach ($archiveGroup in $archiveGroups){
Set-Location $path
$thisName = $archiveGroup.name
write-verbose "Create new sub folder for archive $thisName"
New-Item -Name $thisName -itemType directory
# Copy logs to relevant year folder
Write-Verbose "Moving archive files $thisName to $pwd\$thisName"
$archiveGroup | % {$_.Group | % {move-item $_ -destination ($archiveGroup.name)}}
}
Write-Verbose "$ArchivePath = $pwd"
#$global:ArchivePath = $pwd.path
Write-Verbose "$global:ArchivePath = $pwd"
return $ArchivePath
}
Create-New-Folder-Structure E:\Archives\LatestArchiveFiles
Write-Verbose $ArchivePath
Advertisement