다음을 수행하기 위해 다음 Powershell 스크립트를 작성했습니다.
- 모든 하위 폴더의 모든 파일을 폴더의 루트로 이동
- 모든 하위 폴더 삭제
- 마지막으로 모든 파일이 루트로 이동되면 모든 json 파일을 삭제합니다.
내 powershell 스크립트:
Get-ChildItem -Path ./-Recurse -File | Move-Item -Destination ./; Get-ChildItem -Path ./-Recurse -Directory | Remove-Item;
Get-ChildItem *.json | foreach { Remove-Item -Path $_.FullName }
cd를 사용하여 각 폴더의 작업 디렉토리를 변경해야 합니다. 어떻게 폴더 이름을 전달하고 각 폴더에 대해 위의 스크립트를 실행할 수 있습니까?
--> 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
상위 폴더 이름을 전달하여 상위 폴더의 각 하위 폴더를 통과하고 각 하위 폴더에 대해 독립적으로 powershell 스크립트를 실행하려면 어떻게 해야 합니까?
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
- 답변 # 1
이것이 내가 한 일입니다.
$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 }
- 답변 # 2
Foreach-Object 블록에 프로세스를 넣습니다. 이렇게 하면 상위 디렉터리를 대상으로 지정하고 그 안에 있는 각 하위 폴더를 처리할 수 있습니다. 이것은 @Theo가 언급한 것과 같은 파일 이름 충돌을 고려하지 않습니다.
$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 } }
파일 이름 충돌(두 개 이상의 파일이 동일한 이름을 갖지만 다른 하위 폴더에 있음)에 대해 생각했습니까? Get-ChildItem -Path <여기에 실제 경로 삽입 >?
Theo2021-12-09 01:18:10