Reputation: 23
I would like a powershell script that would move files into a folder based upon the date of the file and then move into subfolders based upon the first 3 characters of the file names. I have been able to move the files to a dated folder, but do not know how to continue with powershell to create subfolders and move files to correct date subfolder. This is what I have and is working for the date:
Get-ChildItem \\servername\path\path\path\path\New_folder\*.* -Recurse | foreach {
$x = $_.LastWriteTime.ToShortDateString()
$new_folder_name = Get-Date $x -Format yyMMdd
$des_path = "\\servername\path\path\path\path\$new_folder_name"
if (test-path $des_path){
move-item $_.fullname $des_path
} else {
new-item -ItemType directory -Path $des_path
move-item $_.fullname $des_path
}
}
Upvotes: 2
Views: 540
Reputation: 5232
With the SubString()
method you can extract a particular part of a given string:
$SourcePath = '\\servername\path\path\path\path\New_folder'
$DestinationRoot = '\\servername\path\path\path\path'
Get-ChildItem $SourcePath -Recurse -File |
ForEach-Object {
$timeStamp = Get-Date $( $_.LastWriteTime) -Format 'yyMMdd'
$FirstThreeLettersFromFileName = $_.BaseName.SubString(0,3)
$destinationPath = "$DestinationRoot\$timeStamp\$FirstThreeLettersFromFileName"
if (-not (Test-Path -Path $destinationPath)) {
New-Item -ItemType Directory -Path $destinationPath
}
Move-Item -Path $_.fullname -Destination $destinationPath
}
Upvotes: 3