Howdy all of you smart people! I am a bit out of my depth and thought I would ask a question to see if someone with a higher IQ could at least point me in the right direction.
I have a share with a lot of single lvl subfolders all with similar names in format (xxxxxx_x) Inside of each folder there are several files:
- half will start with the same prefix "xxxxxx_x" as the parent folder
- other half has another prefix of 10 digits followed by the parent folder prefix:"yyyyyyyyyy-xxxxxx_x"
I was asked to move files to a new location where I have already scripted a deployment of same folder structure but of course the new ask is for the files to be split based on the above two naming conventions.
TL;DR: So to summarize, how can I move a batch of files from multiple subfolders to other location based on a part of the filename? (prefix)
typical example: c:\share\123456_2\123456_2-filename.xls should go to d:\share\123456_2 while c:\share\123456_2\1234567890-123456_2-filename.xls should go to E:\share\123456_2
I could get the files moved and folders created (if missing) using below but how do I only target files that start with the same string (0,8)?
dir | %{
$id = $_.Name.SubString(0,8);
if(-not (Test-Path $id)) {mkdir $id};
mv $_ "D:\share\$_";}
CodePudding user response:
Well, one way to do this is using the -Split
operator, or method to get just the first part of the broken string and check to see if it contains the underscore character (_
); since that seems to follow the naming scheme.
Get-ChildItem |
ForEach-Object -Process {
$destination = $_.Name.Split('-')[0]
if ($destination -match "_") {
Move-Item -LiteralPath $_.FullName -Destination "D:\share\$destination" -WhatIf
}
}
Given that you're not looking to move the other files, this will only move the files that have the same beginning.
Remove the -WhatIf
safety common parameter once you've dictated the results are what you're after.