I started learing powershell two weeks ago. I have the following folders structure
C:\not prepared\Not ready
ABCD_EFGH-whatever\work
IJK-whatever\work
LMN-whatever\work
OPRSTU_WXYZ-whatever\work
C:\Already ready
ABCD_EFGH
IJK
LMN
OPRWXY
The script will run from C:\Already ready
. I want to move each work
folder from "Not ready\*\"
to "Already ready\*"
to get
C:\not prepared\Not ready
ABCD_EFGH-whatever
IJK-whatever
LMN-whatever
OPRSTU_WXYZ-whatever
C:\Already ready
ABCD_EFGH\work
IJK\work
LMN\work
OPRWXY\work
I don't want to specify exact folder names, as those may change. Only first 3 characters from Not ready
and Already ready
subfolders matches. I guess I should read all subfolders' names from both locations, then put them in a array and compare names one by one. What's more, not all folders may always be present in C:\not prepared\Not ready
.
Is there are smarter way to do it? Please give me a hint or example.
CodePudding user response:
Get-Item 'C:\not prepared\Not ready\*\work' | ForEach-Object {
# Derive the destination dir's name from the parent directory name,
# by taking the string before "-". To also split by "_", use:
# $destDir = ($_.Parent.Name -split '[-_]')[0]
# To take just the first 3 characters, use:
# $destDir = $_.Parent.Name.Substring(0, 3)
$destDir = ($_.Parent.Name -split '-')[0]
# Handle the lone exception to the name mapping.
if ($_.Parent.Name -like 'OPRSTU_WXYZ-*') { $destDir = 'OPRWXY' }
# Make sure that the destination dir. exists.
$null = New-Item -ErrorAction Stop -Force -Type Directory $destDir
# Perform the move.
$_ | Move-Item -Destination $destDir -WhatIf
# If desired, remove the parent dir. of the source dir.
Remove-Item -LiteralPath $_.Parent.FullName -Recurse -Force -WhatIf
}
Note: The -WhatIf
common parameter in the command above previews the operation. Remove -WhatIf
once you're sure the operation will do what you want.
Note: The solution above assumes two things:
Each source
work
folder uniquely maps to a destination folder.If the destination folder happens to exist already, it is assumed not to already have a
work
subfolder.