What I have so far:
Get-ChildItem -Path "\\Networkdrive\Folder1\PROD- TEST\Successful" -Recurse |
Where-Object name -match '\w{10}_\w{3}' |
Move-Item -destination "\\Networkdrive\Folder1\Archive- TEST\Archive_PROD_TEST\Successful" -Verbose
Inside of : \\Networkdrive\Folder1\PROD- TEST\Successful
are folders that look like: 9ce8eab8-cefe-4ec9-9158-ff40612d5c47
and then in them are more folders that have criteria 10 numbers with an underscore (_
) and then followed by 3 numbers.
I want to move the 9ce8eab8-cefe-4ec9-9158-ff40612d5c47
folder if any subfolder contains the criteria of 10 characters followed by an _
and then and other 3 characters to \\Networkdrive\Folder1\Archive- TEST\Archive_PROD_TEST\Successful
, but I want to leave the Structure and files alone.
Right now the code just grabs the folders inside and then moves them, but leaves the 9ce8eab8-cefe-4ec9-9158-ff40612d5c47
folders alone. I want 9ce8eab8-cefe-4ec9-9158-ff40612d5c47
to be moved too.
CodePudding user response:
Although not really clear what the subfolder naming convention is (you talk about numbers), so below I'm using this pattern: \d{10}_\d{3}
.
If however these are HEX digits, you need to use pattern [0-9a-f]{10}_[0-9a-f]{3}
Try:
$sourcePath = '\\Networkdrive\Folder1\PROD- TEST\Successful'
$destination = '\\Networkdrive\Folder1\Archive- TEST\Archive_PROD_TEST\Successful'
$folderPattern = '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
$subdirPattern = '\d{10}_\d{3}' # if the name must match FULLY, use anchors: '^\d{10}_\d{3}$'
Get-ChildItem -Path $sourcePath -Directory | Where-Object {$_.Name -match $folderPattern} | ForEach-Object {
# capture the folders FullName for when we hit the catch block in case of error
$targetFolder = $_.FullName
if (@(Get-ChildItem -Path $targetFolder -Directory | Where-Object { $_.Name -match $subdirPattern }).Count) {
# one or more subfolders found with name matching the $subdirPattern, so move the folder
Write-Host "Moving folder '$targetFolder'"
try {
Move-Item -Path $targetFolder -Destination $destination -Force -ErrorAction Stop
}
catch {
Write-Warning "Error moving folder '$targetFolder':`r`n$($_.Exception.Message)"
}
}
}
CodePudding user response:
Assuming that the folders named XXXXXXXXX_XXX
are the immediate children of the folders named XXXXXXX-XXXX-XXXX-XXXXXXXXXXXX
, then you can:
- find the folders that match your desired pattern, and
- get the
Parent
property on these objects.
For example, I would use this:
Get-ChildItem -Path "\\Networkdrive\Folder1\PROD-TEST\Successful\*\*" -Directory |
Where-Object name -match '\w{10}_\w{3}' |
Get-ItemPropertyValue -Name Parent |
Move-Item -Destination "\\Networkdrive\Folder1\Archive- TEST\Archive_PROD_TEST\Successful" -Verbose
Note that this simple strategy works only if XXXXXXXXXX_XXX
directories are always at the same depth relative to the folders that needs to be moved, because Parent
get's you exactly one level.