개요
Copy-Item은 항목을 원본에서 지우지 않고 다른 위치에 복제하는 cmdlet이다. 같은 네임스페이스(같은 프로바이더) 안에서만 복사할 수 있다 — 파일을 폴더로 복사할 수는 있어도 인증서 저장소로 복사할 수는 없다. -Destination에 새 이름을 지정하면 복사와 동시에 이름도 바꿀 수 있다.
사용법
| |
매개변수
| 매개변수 | 설명 |
|---|---|
-Path / -Destination | 원본과 대상 경로. -Destination 생략 시 현재 디렉터리 |
-Recurse | 하위 디렉터리·파일까지 복사 |
-Container | 디렉터리 구조를 유지할지 여부(기본 $true). $false로 주면 내용만 평평하게 복사(동명 파일은 덮어써짐) |
-Filter / -Include / -Exclude | 31장과 같은 규칙 — -Filter는 프로바이더 수준, -Include/-Exclude는 후처리(둘 다 -Path의 와일드카드 매칭 결과에만 적용되고 -Recurse로 발견된 하위 항목에는 적용 안 됨) |
-Force | 읽기 전용 항목도 덮어쓰기 허용 |
-ToSession / -FromSession | 원격 컴퓨터로/에서 파일을 복사할 PSSession 지정(11부에서 원격 세션을 본격적으로 다룬다) |
예시
| |
주의사항·함정
-Include/-Exclude는 -Recurse로 발견된 항목까지 걸러주지 않는다: 이 두 매개변수는 -Path에 지정한 와일드카드가 1차로 펼쳐진 결과에만 적용되고, 그 하위로 재귀하며 새로 찾은 항목에는 적용되지 않는다. 재귀 중에 세밀한 패턴으로 걸러야 한다면, 예시처럼 Get-ChildItem -Recurse -Filter로 먼저 대상을 찾은 뒤 Copy-Item으로 파이프하는 방식이 더 예측 가능하다.
-Container $false는 동명 파일을 조용히 덮어쓴다: 서로 다른 하위 디렉터리에 있던 같은 이름의 파일들이 평평한 복사 과정에서 마지막에 처리된 파일로 덮어써진다. 파일 이름이 겹칠 가능성이 있는 트리를 평평하게 합칠 때는 사전에 이름 충돌 여부를 확인해야 한다.
대상 디렉터리가 없으면 결과가 헷갈릴 수 있다: Copy-Item -Path "C:\Logfiles\*" -Destination "C:\Drawings" -Recurse에서 C:\Drawings가 아예 존재하지 않으면, 여러 파일이 있는 트리 전체가 Drawings라는 이름의 파일 하나로 뭉개질 수 있다. 대상이 디렉터리인지 사전에 Test-Path -PathType Container로 확인하는 습관이 안전하다(39장에서 Test-Path를 다룬다).
이식성: copy/xcopy/robocopy가 별도 명령으로 나뉜 CMD와 달리, PowerShell은 단일 파일 복사부터 재귀 복사, 원격 전송까지 Copy-Item 하나의 매개변수 조합으로 표현한다. Bash의 cp -r, scp에 각각 -Recurse, -ToSession/-FromSession이 대응한다.
![Featured image of post [PowerShell] 34. Copy-Item — 복사](/post/powershell/copy-item-command-copy-file-powershell/wordcloud_hu_38b2e9a9eb8c0010.webp)
![[PowerShell] 32. Set-Location/Push-Location/Pop-Location](/post/powershell/set-location-push-pop-location-powershell/wordcloud_hu_b555782207661429.webp)
![[PowerShell] 33. New-Item — 파일·디렉터리 생성](/post/powershell/new-item-command-create-file-directory-powershell/wordcloud_hu_c75a1ced5c6a3aa3.webp)
![[PowerShell] 34. Copy-Item — 복사](/post/powershell/copy-item-command-copy-file-powershell/wordcloud_hu_ebeda4bcc9a1c9ff.webp)
![[PowerShell] 35. Move-Item/Rename-Item — 이동과 이름 변경](/post/powershell/move-rename-item-command-powershell/wordcloud_hu_cb2a58d584784b24.webp)
![[PowerShell] 36. Remove-Item — 삭제](/post/powershell/remove-item-command-delete-powershell/wordcloud_hu_85e27bcaf405bed4.webp)
![[PowerShell] 30. PSDrive와 프로바이더 개념](/post/powershell/psdrive-provider-concept-powershell/wordcloud_hu_48d84a64f7474c4.webp)
![[PowerShell] 31. Get-ChildItem — 파일·디렉터리 목록](/post/powershell/get-childitem-command-file-directory-list-powershell/wordcloud_hu_3e00080e70b06aa7.webp)
![[PowerShell] 39. Test-Path — 경로 존재 확인](/post/powershell/test-path-command-check-path-powershell/wordcloud_hu_8b7ea3ad5761442.webp)