[파워쉘] 도토리 수납기

주의 사항

  1. 사소한 텍스트 파일로 연습해보고 사용하면 좋을겁니다.
  2. 윈도우 터미널 + 파워쉘 7 조합에서 안정적으로 활용했으니 참고하시기 바랍니다.
  3. 저는 구드데탑에서 이것들이랑 파일명 변경 스크립트로 구드 정리를 합니다.
  4. 파워쉘에서 쓰는 명령어를 만든 것이고 해당하는 과정을 모두 적용해야 사용 가능합니다.
  5. 진짜 중요한 파일은 수동으로 옮기는 것을 추천합니다.
  6. 엄청난 주의 사항이 있음
    같은 SSD나 HDD같은 스토리지(드라이브) 내에서는 거의 바로바로 바뀌는 수준의 모습을 보이지만,
    혹여 물리적으로 다른 스토리지로 이동하는 경우에는 윈도우탐색기의 [잘라내기/붙여넣기] 기능이니
    완전히 작업이 끝날 때까지 파워쉘을 절대 끄면 안됩니다.
    무슨 일이 일어날지 모름.
    그래서 같은 스토리지 내에서 파일들을 폴더정리만 할 때만 사용하세요.
    [잘라내기/붙여넣기]를 하고 싶으면 윈도우 탐색기에서 실행하세요.

설정법

  1. 아래 코드를 복사한다.
    function Move-NumberedFile {
      [CmdletBinding()]
      param (
        [Parameter(ValueFromPipeline = $true, Mandatory = $true, Position = 0)]
        [string]$sourcePath,
        [Parameter(Mandatory = $true, Position = 1)]
        [string]$destinationPath
      )
    
      process {
        $fileName = [System.IO.Path]::GetFileName($sourcePath)
        $extension = [System.IO.Path]::GetExtension($sourcePath)
        $destinationFile = Join-Path $destinationPath $fileName
        $fileNumber = 1
    
        while (Test-Path $destinationFile) {
          $newFileName = "{0}_{1}{2}" -f ([System.IO.Path]::GetFileNameWithoutExtension($fileName)), $fileNumber, $extension
          $destinationFile = Join-Path $destinationPath $newFileName
          $fileNumber++
        }
    
        Move-Item -Path $sourcePath -Destination $destinationFile
      }
    }
    
    function Move-Files {
      param (
        [String]$searchFileName = "",
        [String]$rootFinalDir = $PWD,
        [Switch]$Recurse,
        [Switch]$Directory
      )
    
      $fitFiles = Get-ChildItem -Path $rootFinalDir -Filter "*$searchFileName*" -Recurse:$Recurse -File:(!$Directory) -Directory:$Directory -ErrorAction Stop
    
      if ($fitFiles.Count -eq 0) { 
        Write-Host "No files matching the specified pattern found in this path.`r`nExit."
      } else {
        $destinationDir = Join-Path $rootFinalDir $searchFileName
        if (-not (Test-Path -Path $destinationDir)) {
          New-Item -Path $destinationDir -ItemType Directory | Out-Null
        }
    
        $fitFiles | ForEach-Object {
          $_ | Move-NumberedFile -destinationPath $destinationDir
        }
        Get-ChildItem -Path ${destinationDir} -ErrorAction Stop | Sort-Object -Property Extension, Name, LastWriteTime | Format-Table -AutoSize -Property @{ Name = 'Length'; Expression = { Convert-Size $_.Length } }, LastWriteTime, Name
      }
    }
    Set-Alias m Move-Files
    Set-AliasMove-Files
    
    function Move-CurrentFiles {
      $subDirectories = Get-ChildItem -Path $PWD -Directory -ErrorAction SilentlyContinue
      if ($null -eq $subDirectories) {
        Write-Host "There are no subdirectories in this directory. Exiting."
        return
      }
    
      foreach ($subDir in $subDirectories) {
        $filesToMove = Get-ChildItem -Path $PWD -Filter "*$($subDir.Name)*" -File -ErrorAction SilentlyContinue
        if ($null -ne $filesToMove) {
          $destinationPath = Join-Path -Path $PWD -ChildPath $subDir.Name
          $filesToMove | Move-NumberedFile -DestinationPath $destinationPath
        }
      }
    
      $remainingFiles = Get-ChildItem -Path $PWD -File -ErrorAction SilentlyContinue
      if ($null -ne $remainingFiles) {
        $etcFolder = Join-Path -Path $PWD -ChildPath "_etc_"
        if (-not (Test-Path -Path $etcFolder -PathType Container)) {
          New-Item -Path $etcFolder -ItemType Directory | Out-Null
        }
        $remainingFiles | Move-NumberedFile -DestinationPath $etcFolder
      }
    }
    Set-Alias mm Move-CurrentFiles
    Set-Alias ㅗㅗ Move-CurrentFiles  
  2. 파워쉘에 notepad $PROFILE.AllUsersAllHosts 를 입력한다. (만약 컴퓨터 윈도우 설치 후 최초로 실행하는 경우 나오는 메시지 박스의 '예' 누르기)
  3. 붙여넣고 저장한다.
  4. [PowerShell 7] 설정하기 - 7r 채널 에서 준비사항 2 실행 (이미 한경우는 상관 없음)
  5. 파워쉘 재시작

사용법

파일검색으로 이동하기

  • 입력한 텍스트로 현재경로에 새로운 경로를 생성하고 입력한 텍스트를 포함하는 파일명을 가진 모든 파일을 옮기며, 
    완전히 이름이 중복되는 파일이 있는 경우 뒤에 ‘_숫자(넘버링)’ 붙이기
    만일 아무 것도 입력하지 않으면, 현재 폴더 경로 내 모든 파일이 뒤에 '_숫자'가 붙은 채 그대로 유지
    1. m 대신 ㅗ 사용가능
    2. 하위경로를 제외한 현재 경로 내에서 공통되는 파일명(텍스트)을 입력

      m -searchFileName [원하는텍스트] -rootFinalDir [만든폴더저장할위치(기본값:현재폴더)지정]
      m [원하는텍스트] [원하는_저장경로]

    3. -Recurse나 -Directory 는 뒤에 인수 없이 그냥 사용
      1. -Recurse 입력시 자동으로 모든 하위 경로 내에 있는 매칭되는 파일만 지정
      2. -Directory 입력시 자동으로 현재 경로 내 매칭되는 폴더만 지정
      3. 둘다 입력시 자동으로 모든 하위 경로 내에 폴더만 지정
        • 아래는 두개다 입력한 버전의 명령어

          m -searchFileName [원하는텍스트] -rootFinalDir [만든폴더저장할위치(기본값:현재폴더)지정] -Recurse -Directory

실행시 현재 경로 내 폴더명으로 각 파일 자동이동하기

  • 현재 경로에 존재하는 모든 경로명(폴더명)을 불러와서 해당하는 경로명을 포함하는 개별파일들을 각각 경로에 이동 시킴
    • 만일 아무 것도 입력하지 않으면, 현재 폴더 경로 내 모든 파일이 '_etc_' 폴더로 이동됨
    • 아래 명령어만 원하는 경로에서 실행하면 됩니다.

      mm 혹은 ㅗㅗ 입력 후 엔터

    • 간단 설명: 각 스트id로 된 폴더들이 있고, 파일명에 모두 스트id를 포함한다고 할 때,
      각 스트폴더에 스트영상이 이동하고, 
      존재하지 않는 폴더인 경우 ‘_etc_‘ 폴더로 전부 이동시켜 깔끔한 폴더관리 쌉가능