Warm tip: This article is reproduced from serverfault.com, please click

Move subfolder elsewhere and rename based on parent using PowerShell

发布于 2020-11-27 14:22:28

I have many report folders under different parent folders that has the following structure:

C:\Users\USER\Downloads\LTFT01\Report
C:\Users\USER\Downloads\LTFT02\Report
C:\Users\USER\Downloads\LTFT03\Report

What I want to do is, if any of the report folders are non-empty, then move that report folder elsewhere and rename the folder with the original parent folder in the name. Such as LTFT01Report and LTFT02Report.

I have the 'test if it's non-empty' bit ready, but I have no idea what to do from here. I don't know really how foreach works so I haven't been able to implement that (even after searching!)

If (Test-Path -Path "C:\Users\USER\Downloads\*\Report\*"

Edit: It seems I need to clarify for some the following:

  1. I'm new to coding, and new to PowerShell as of this week
  2. I've googled a ton and found a bunch of answers, but nothing pertinent to my question (directly) or it's left me confused :(
  3. I would really appreciate a nudge in the right direction rather than a git gud.
  4. I think I need a foreach, hence my last line of the question, but not sure. Again - newbie here!
Questioner
Adil.yuken
Viewed
0
Adil.yuken 2020-11-29 05:56:00

OP here!

So I've been able to create an answer based on some research:

#Get report folder path
$ReportPath = "C:\Users\USER\Downloads\*\Report"
$MasterReportPath = "C:\Users\USER\Downloads\MasterReports"

#Rename report folder to {currentparentname}report
Get-Item -Path $ReportPath | ForEach-Object {$a = $_.FullName | split-path -Parent | split-path -leaf; Rename-Item -Path $_.FullName -NewName $a"Report"}

#Move report folder
$AnyNamedReportFolder = Get-Item "C:\Users\USER\Downloads\*\*Report*" -Exclude *.jmx, *.csv
Move-Item -Path $AnyNamedReportFolder -Destination $MasterReportPath

Definitely isn't elegant, but does the job. Since I have the main answer to this question, I'll mark it as answered. However there is an issue with this, which is that if this is run multiple times then same named folders will not move (since it doesn't append a unique number or character). I've highlighted this in a new question here, should you be interested. If all you need is a one time working script, then the above script worked for me.

Moving Same Name Folders into Another Folder