I have put together the following Powershell script to do the following:
- Move all files from all the sub-folders into the root of the folder
- Delete all sub-folders
- Finally once all files have been moved to the root, delete any json files
My powershell script:
Get-ChildItem -Path ./ -Recurse -File | Move-Item -Destination ./ ; Get-ChildItem -Path ./ -Recurse -Directory | Remove-Item;
Get-ChildItem *.json | foreach { Remove-Item -Path $_.FullName }
I am having to use cd to change my working directory for each folder, How can I pass a folder name and have the the above script executed for each folder.
--> So there is a parent folder
--> There are 100s of Sub-Folders in the parent Folder
--> Each Sub-folder have many sub-folders and many files
How can I pass the parent folder name so it will go through each sub folder in the parent folder and run the powershell script independently for each sub-folder?
ParentFolder
Child-Sub-Folder1 <-- Move all files in the sub-folders to the root folder Child-Sub-Folder1
Child-Sub-Folder2 <-- Move all files in the sub-folders to the root folder Child-Sub-Folder2
Child-Sub-Folder3 <-- Move all files in the sub-folders to the root folder Child-Sub-Folder3
CodePudding user response:
Put the processes in Foreach-Object blocks. This lets you target the parent directory and process each subfolder in it. This does not take into account file name collisions like @Theo commented.
$parentFolder = "PathToParent"
Get-ChildItem -Path $parentFolder | ForEach-Object {
$subFolder = $_.FullName
Get-ChildItem -Path $subFolder -Recurse -File | ForEach-Object {
#Move-Item $_.FullName -Destination $subFolder
}
Get-ChildItem -Path $subFolder -Recurse -Directory | Remove-Item
Get-ChildItem -Path $subFolder "*.json" | ForEach-Object {
Remove-Item -Path $_.FullName
}
}
CodePudding user response:
This is what I ended up doing:
$dir = dir "D:\MyFolder\" | ?{$_.PSISContainer}
foreach ($d in $dir){
$name = $d.FullName
$name
Get-ChildItem -Path $name -Recurse -File | Move-Item -Destination $name ; Get-ChildItem -Path $name -Recurse -Directory | Remove-Item -Confirm:$false
Get-ChildItem -Path $name *.json | foreach { Remove-Item -Path $_.FullName } -Confirm:$false
Get-ChildItem -Path $name *.heic | foreach { Remove-Item -Path $_.FullName } -Confirm:$false
}