개요
논리 연산자는 여러 개의 조건식을 하나의 참/거짓 값으로 묶는다. -and, -or, -xor, -not(또는 !) 네 가지가 있으며, 20장의 비교 연산자와 짝을 이뤄 Where-Object·if 문에서 복합 조건을 표현하는 데 쓰인다.
정신 모델에서 중요한 것은 “단락 평가(short-circuit evaluation)“다. -and로 연결된 조건에서 왼쪽이 이미 거짓이면 오른쪽은 아예 평가하지 않고, -or로 연결된 조건에서 왼쪽이 이미 참이면 오른쪽을 평가하지 않는다. 이 덕분에 if문처럼 조건에 따라 실행 여부를 결정하는 용도로도 논리 연산자를 활용할 수 있다.
사용법
| |
-and, -or, -xor는 모두 같은 우선순위를 가지며 왼쪽에서 오른쪽 순서로 평가된다(연산자 우선순위 전체는 about_Operator_Precedence 참고).
종류
| 연산자 | 참이 되는 조건 |
|---|---|
-and | 양쪽 모두 참일 때 |
-or | 둘 중 하나라도 참일 때 |
-xor | 정확히 한쪽만 참일 때(배타적 논리합) |
-not / ! | 뒤따르는 값을 반전 |
예시
| |
주의사항·함정
단락 평가는 부작용이 있는 표현식에서 특히 중요하다: $false -and (Remove-Item file.txt)처럼 오른쪽에 실제 동작(파일 삭제)이 들어 있다면, 왼쪽이 거짓인 순간 오른쪽은 절대 실행되지 않는다. 조건과 실행할 동작을 논리 연산자로 압축해 쓸 때는 이 점을 반드시 의도해야 한다.
-xor는 스위치 매개변수처럼 두 조건 다 참인 경우를 걸러낸다: “둘 중 하나만"이라는 요구사항을 -or로 잘못 표현하면 둘 다 참인 경우까지 포함되는 실수가 흔하다. 정확히 하나만 참이어야 한다면 -xor를 써야 한다.
정수의 불리언 변환 규칙을 정확히 알아야 한다: 정수 0은 거짓($false)으로, 그 외 모든 정수(음수 포함)는 참($true)으로 변환된다. if (-1) { ... }도 참으로 평가되는 것은 이 규칙 때문이며, C 계열 언어의 직관과 다르지 않지만 명시적으로 확인해 두는 것이 좋다.
이식성: Bash의 &&/||도 단락 평가를 지원한다는 점은 같지만, Bash는 이 연산자를 명령어 사이(파이프라인 흐름 제어)에 쓰는 경우가 많은 반면 PowerShell의 -and/-or는 값·조건식 사이에 쓰는 순수한 논리 연산자다. CMD에는 이런 논리 연산자가 없어 if를 중첩하거나 ERRORLEVEL을 조합하는 방식으로 흉내 낸다.
![Featured image of post [PowerShell] 21. 논리 연산자와 조건식 조합 — -and/-or/-not](/post/powershell/logical-operators-and-or-not-powershell/wordcloud_hu_c32d5121cd46d21b.webp)
![[PowerShell] 19. Compare-Object — 객체 비교(diff)](/post/powershell/compare-object-command-diff-powershell/wordcloud_hu_85c73f8cde4535c3.webp)
![[PowerShell] 20. 비교 연산자 — -eq/-like/-contains/-in](/post/powershell/comparison-operators-eq-like-contains-in-powershell/wordcloud_hu_e39e3d06b7800d57.webp)
![[PowerShell] 21. 논리 연산자와 조건식 조합 — -and/-or/-not](/post/powershell/logical-operators-and-or-not-powershell/wordcloud_hu_751168d59de9154c.webp)
![[PowerShell] 22. -split/-join 연산자](/post/powershell/split-join-operators-powershell-strings/wordcloud_hu_284bbfdffb9b3b18.webp)
![[PowerShell] 23. 타입 캐스팅과 [type] 접근자](/post/powershell/type-casting-type-accelerator-powershell/wordcloud_hu_e3ac5e77eecdb3c5.webp)
![[PowerShell] 54. if/elseif/else — 조건 분기](/post/powershell/if-elseif-switch-condition-powershell/wordcloud_hu_fd68a53ddac2fa5a.webp)
![[PowerShell] 12. Where-Object — 필터링](/post/powershell/where-object-command-filter-pipeline-powershell/wordcloud_hu_75843f29a19f2cc5.webp)
![[PowerShell] 39. Test-Path — 경로 존재 확인](/post/powershell/test-path-command-check-path-powershell/wordcloud_hu_8b7ea3ad5761442.webp)
![[PowerShell] 42. 배열과 컬렉션 기초](/post/powershell/arrays-collections-powershell/wordcloud_hu_c295cc73d4592ae5.webp)