Can anyone help we with a powershell script to create folders and subfolder based on the the filename and then move the said file to last subfolder.
For instance I have files named as:
2017061400074000-F1C11A22FAEE3B82F21B330E1B786A39.jpg
2017061612203200-F1C11A22FAEE3B82F21B330E1B786A39.jpg
2019122616073600-F1C11A22FAEE3B82F21B330E1B786A39.mp4
2020011703483000-F1C11A22FAEE3B82F21B330E1B786A39.mp4
Then what I aim is:
For 2017061400074000-F1C11A22FAEE3B82F21B330E1B786A39.jpg
Create folder 2017 then subfolder 06 then the final subfolder 14 (basically based on the first 8 strings which is a date). Then move the file to subfolder 14.
If the folder already exist then just move the file there. Then run this for all of the files in the main folder where the main files are.
Thanks everyone!
Really appreciate any help.
>Solution :
# Replace "C:\path\to\your\files" with the actual path to the folder containing your files
$sourcePath = "C:\path\to\your\files"
# Get a list of all files in the source folder
$files = Get-ChildItem -Path $sourcePath -File
foreach ($file in $files)
{
# Extract the first 8 characters from the file name as the date
$dateString = $file.BaseName.Substring(0, 8)
# Parse the date string to get the year, month, and day
$year = $dateString.Substring(0, 4)
$month = $dateString.Substring(4, 2)
$day = $dateString.Substring(6, 2)
# Create the destination folder path
$destinationFolder = Join-Path -Path $sourcePath -ChildPath "$year\$month\$day"
# Create the destination folder if it doesn't exist
if (-not (Test-Path -Path $destinationFolder -PathType Container))
{
New-Item -ItemType Directory -Path $destinationFolder | Out-Null
}
# Move the file to the destination folder
Move-Item -Path $file.FullName -Destination $destinationFolder
}
All files from directory provided in $sourcePath will be move