개요
Test-Path는 경로가 실제로 존재하는지, 또는 경로 문법 자체가 유효한지를 Boolean으로 알려주는 cmdlet이다. 34장에서 언급했듯 Copy-Item 같은 명령을 실행하기 전 대상이 이미 있는지, 컨테이너인지 미리 확인하는 안전장치로 자주 쓰인다.
사용법
| |
매개변수
| 매개변수 | 설명 |
|---|---|
-Path | 확인할 경로. 모든 구성 요소가 존재해야 $true |
-PathType(별칭 -Type) | Leaf(파일 등 자식이 없는 항목), Container(디렉터리·레지스트리 키 등), Any(둘 중 하나) |
-IsValid | 실제 존재 여부가 아니라 경로 문법이 유효한지만 검사(대상이 없어도 $true일 수 있음) |
-NewerThan / -OlderThan(FileSystem 동적 매개변수, PowerShell 7.5+에서 기능 확장) | 지정한 날짜 기준으로 파일·디렉터리의 최신/오래됨 여부 확인 |
-Filter / -Include / -Exclude | 31장과 같은 규칙 |
예시
| |
주의사항·함정
레지스트리 “값"에는 Test-Path가 항상 False를 반환한다: Test-Path는 레지스트리 키(컨테이너)의 존재는 정확히 확인하지만, 38장에서 다룬 레지스트리 값(Item Property)의 존재는 확인하지 못하고 값이 실제로 있어도 False를 준다. 값의 존재를 확인하려면 Get-ItemProperty로 조회를 시도하고 예외나 $null 여부로 판단해야 한다. 공식 문서도 이 동작을 명시적으로 “모든 프로바이더에서 올바르게 동작하지는 않는다"고 경고한다.
빈 문자열과 공백 문자열, $null은 서로 다르게 처리된다: 공백만 있는 문자열(' ')이나 빈 문자열('')을 넘기면 $false를 반환하지만, $null이나 빈 배열을 넘기면 비종료 오류가 난다(-ErrorAction SilentlyContinue로 억제 가능). 사용자 입력을 그대로 Test-Path에 넘기는 스크립트라면 이 세 가지 입력이 각각 다르게 처리된다는 점을 감안해야 한다.
-IsValid와 -PathType을 함께 쓰면 -PathType이 무시될 수 있다: PowerShell 6.1.2까지는 두 매개변수를 같이 쓰면 -PathType이 조용히 무시되고 문법 검사만 수행된다(알려진 이슈). 정확한 동작이 필요하면 두 검사를 별도의 Test-Path 호출로 나누는 편이 안전하다.
이식성: CMD의 if exist, Bash의 [ -e ]/[ -f ]/[ -d ]에 각각 Test-Path, -PathType Leaf, -PathType Container가 대응한다. 다만 PowerShell은 파일 시스템뿐 아니라 레지스트리 키 같은 다른 프로바이더 경로에도 같은 검사를 적용할 수 있다는 점이 더 넓다.
![Featured image of post [PowerShell] 39. Test-Path — 경로 존재 확인](/post/powershell/test-path-command-check-path-powershell/wordcloud_hu_362b623905fe6977.webp)
![[PowerShell] 37. Get-Content/Set-Content/Add-Content](/post/powershell/get-set-add-content-command-powershell/wordcloud_hu_f8c9bc65df09a5fa.webp)
![[PowerShell] 38. Get-ItemProperty/Set-ItemProperty](/post/powershell/get-set-itemproperty-command-powershell/wordcloud_hu_4fee0f6df596d89c.webp)
![[PowerShell] 39. Test-Path — 경로 존재 확인](/post/powershell/test-path-command-check-path-powershell/wordcloud_hu_8b7ea3ad5761442.webp)
![[PowerShell] 40. 레지스트리 프로바이더(Registry:) 다루기](/post/powershell/registry-provider-hklm-hkcu-powershell/wordcloud_hu_cf90c98823ba3b1c.webp)
![[PowerShell] 41. 변수와 데이터 타입](/post/powershell/variables-data-types-powershell/wordcloud_hu_6051f7a36d4700ee.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] 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)