Trying to index and search for a file within 8K files and 2K folders..
Is there a simple Powershell script that can move all files from folders and/or subfolders into one main folder?
don't need to delete the empty folders but would help.
Trying to index and search for a file within 8K files and 2K folders..
Is there a simple Powershell script that can move all files from folders and/or subfolders into one main folder?
don't need to delete the empty folders but would help.
The fourth example under help -Examples Move-Item
[1] is close to what you need. To move all files under the SOURCE
directory to the DEST
directory you can do this:
Get-ChildItem -Path SOURCE -Recurse -File | Move-Item -Destination DEST
If you want to clear out the empty directories afterwards, you can use a similar command:
Get-ChildItem -Path SOURCE -Recurse -Directory | Remove-Item
[1] https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/move-item
Use .parent
for the parent dir. It can be used recursively: .parent.parent
The other answer led to an error for me because of duplicate files. My code solves this by appending a "_x" to duplicate files. Also the removal should only work, if there are no files left.
$files = Get-ChildItem -Path . -Recurse -File
foreach ($file in $files) {
$dest = Join-Path . $file.Name
if (Test-Path $dest) {
$i = 1
do {
$newName = "$($file.BaseName)_$i$($file.Extension)"
$newDest = Join-Path . $newName
$i++
} while (Test-Path $newDest)
Move-Item -Path $file.FullName -Destination $newDest
} else {
Move-Item -Path $file.FullName -Destination $dest
}
}
Get-ChildItem -Directory | Where-Object {(Get-ChildItem $_ -Recurse -File).count -eq 0} | ForEach-Object {Remove-Item $_ -Recurse}