Trying to do some directory cleanups, and transition from an old methodology to a new one. Currently we've been doing it manually, case-by-case, but I decided to look into automating the process.
This worked in theory until we started extracting more CSV data, and ran into new issues.
What I cannot find an answer for anywhere is "renaming a folder, and if the name exists then merge the two" exactly like you would see in Windows Explorer:
I know this is dangerous - but its the only way I can think of it.
I looked into Copy-Item but since the folders range from a few MB all the way to >20GB (and on average at the larger side). It's too slow to copy, move child items, then delete - plus with about 8000 folders to create and move I don't think there's enough buffer storage.
Is it possible to merge the folders, and sub folders into the newly created one?
This is what I have so far:
# set the working directory
Set-Location "B:\"
# import the CSV file for folder creation
$folders = Import-Csv -Delimiter "," -Header @("ID","caseName","caseNumber") -Path .\export.csv
# begin the loop
ForEach( $folder in $folders ) {
# create the variables
$columnID = $folder.ID
$columnCase = "{0} {1}" -f $folder.caseName, $folder.caseNumber
$columnNewCase = "{1}, {0}" -f $folder.caseName, $folder.caseNumber
# use later to create root folders
$yearAllocation = "20{0}" -f $folder.caseNumber.Substring(0,2)
#
# // MARK: begin main folder creation
#
# "SMITH 12345678" and "12345678, SMITH" do NOT exist
if( (-not ( Test-Path "$columnCase" )) -and (-not ( Test-Path "$columnNewCase" )) ) {
# create the "12345678, SMITH"
New-Item "$columnNewCase" -ItemType Directory
}
# "SMITH 12345678" EXISTS but "12345678, SMITH" does NOT exist
if( ( Test-Path "$columnCase" ) -and (-not ( Test-Path "$columnNewCase" )) ) {
# rename "SMITH 12345678" -> "12345678, SMITH"
Rename-Item "$columnCase" -NewName $columnNewCase -Force
}
# "SMITH 12345678" does NOT exist but "12345678, SMITH" EXISTS
# if( (-not ( Test-Path "$columnCase" )) -and ( Test-Path "$columnNewCase" ) ) {
# # do nothing
# }
# "SMITH 12345678" and "12346578, SMITH" both EXIST
if( ( Test-Path "$columnCase" ) -and ( Test-Path "$columnNewCase" ) ) {
# merge "SMITH 12345678" -> "12345678, SMITH"
}
#
# // MARK: begin ID folder moves
#
# if "98765" folder exists
if( Test-Path "$columnID" ) {
# move "98765" into "12345678, SMITH"
Move-Item "$columnID" -Destination "$columnNewCase"
}
}
In the end I'd hope that we could get something that looks like this currently:
B:\
- 12345
- 23445
- 63574
- 73363
- SMITH 12345678
- JONES 58478945
into:
B:\
- 12345678, SMITH
--- 12345
--- 23445
- 58478945, JONES
--- 63574
--- 73363
and if someone accidentally created a new manual folder:
B:\
- 12345678, SMITH
--- 12345
--- 23445
- 58478945, JONES
--- 63574
--- 73363
- SMITH 12345678
--- 66684
then re-running the script would simply:
B:\
- 12345678, SMITH
--- 12345
--- 23445
--- 66684
- 58478945, JONES
--- 63574
--- 73363
