about_Properties
about_Properties
PowerShell로 일을 하다 보면 어느 순간 "객체"라는 말과 마주치게 돼요. 객체는 그냥 데이터가 아니라, 실제 파일이나 컴퓨터 상태를 대신해 주는 작은 대리인 같은 존재인데요. 이번에는 그 객체가 들고 있는 속성(property) 을 어떻게 확인하고, 어떻게 값을 꺼내 쓰는지 차근차근 살펴볼게요.
출처: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_properties
본문
짧은 설명
이 문서는 PowerShell에서 객체 속성(property)을 사용하는 방법을 설명해요.
자세한 설명
PowerShell은 데이터 저장소의 항목이나 컴퓨터의 상태를 **객체(object)**라는 구조화된 정보 묶음으로 표현해요. 보통은 Microsoft .NET Framework에 속한 객체를 다루게 되지만, PowerShell에서 직접 사용자 객체를 만들 수도 있어요.
객체와 그 객체가 나타내는 항목 사이의 연결은 아주 밀접해요. 객체를 바꾸면, 대개 그 객체가 나타내는 항목도 함께 바뀌거든요. 예를 들어 PowerShell에서 파일을 가져온다고 하면 실제 파일이 넘어오는 게 아니라, 그 파일을 대표하는 FileInfo 객체가 넘어와요. 그리고 이 FileInfo 객체를 바꾸면 실제 파일도 바뀌어요.
대부분의 객체에는 속성(property)이 있어요. 속성은 객체에 딸려 있는 데이터라고 보면 돼요. 객체의 종류에 따라 속성도 달라지는데, 예를 들어 파일을 나타내는 FileInfo 객체에는 IsReadOnly 속성이 있어서, 파일에 읽기 전용 특성이 붙어 있으면 $true를, 아니면 $false를 담고 있어요. 파일 시스템 디렉터리를 나타내는 DirectoryInfo 객체에는 Parent 속성이 있어서 부모 디렉터리의 경로를 담고 있죠.
객체 속성 살펴보기
객체의 속성을 확인하려면 Get-Member cmdlet을 사용해요. 예를 들어 FileInfo 객체의 속성을 보려면 Get-ChildItem cmdlet으로 파일을 나타내는 FileInfo 객체를 가져온 다음, 파이프라인 연산자(|)로 그 FileInfo 객체를 Get-Member에 넘겨주면 돼요. 아래 명령은 pwsh.exe 파일을 가져와 Get-Member로 보내는 모습이에요. $PSHOME 자동 변수는 PowerShell 설치 디렉터리의 경로를 담고 있어요.
Get-ChildItem $PSHOME\pwsh.exe | Get-Member
이 명령의 출력은 FileInfo 객체의 멤버 목록이에요. 여기서 멤버에는 속성과 메서드가 모두 포함돼요. PowerShell에서 작업할 때는 객체의 모든 멤버에 접근할 수 있어요.
속성만 보고 싶고 메서드는 빼고 싶다면, Get-Member cmdlet의 MemberType 매개 변수에 Property 값을 주면 되는데, 아래 예시처럼 하면 돼요.
Get-ChildItem $PSHOME\pwsh.exe | Get-Member -MemberType Property
TypeName: System.IO.FileInfo
Name MemberType Definition
---- ---------- ----------
Attributes Property System.IO.FileAttributes Attributes {get;set;}
CreationTime Property System.DateTime CreationTime {get;set;}
CreationTimeUtc Property System.DateTime CreationTimeUtc {get;set;}
Directory Property System.IO.DirectoryInfo Directory {get;}
DirectoryName Property System.String DirectoryName {get;}
Exists Property System.Boolean Exists {get;}
Extension Property System.String Extension {get;}
FullName Property System.String FullName {get;}
IsReadOnly Property System.Boolean IsReadOnly {get;set;}
LastAccessTime Property System.DateTime LastAccessTime {get;set;}
LastAccessTimeUtc Property System.DateTime LastAccessTimeUtc {get;set;}
LastWriteTime Property System.DateTime LastWriteTime {get;set;}
LastWriteTimeUtc Property System.DateTime LastWriteTimeUtc {get;set;}
Length Property System.Int64 Length {get;}
Name Property System.String Name {get;}
속성을 찾았다면 이제 그것들을 PowerShell 명령에서 자유롭게 쓸 수 있어요.
속성 값 가져오기
한 종류의 객체는 모두 같은 속성을 갖지만, 그 속성의 값은 각각의 객체를 구체적으로 묘사해요. 예를 들어 모든 FileInfo 객체에는 CreationTime 속성이 있지만, 파일마다 그 값은 서로 달라요.
객체 속성의 값을 가져오는 가장 흔한 방법은 멤버 접근 연산자(.)를 쓰는 거예요. 객체를 담은 변수처럼 객체를 가리키는 참조를 쓰거나, 객체를 가져오는 명령을 쓴 다음, 연산자(.)를 붙이고 속성 이름을 이어 쓰면 돼요.
아래 명령은 pwsh.exe 파일의 CreationTime 속성 값을 보여줘요. Get-ChildItem 명령이 pwsh.exe 파일을 나타내는 FileInfo 객체를 돌려주는데, 속성에 접근하기 전에 명령이 반드시 먼저 실행되도록 괄호로 감싸 준 거예요.
(Get-ChildItem $PSHOME\pwsh.exe).CreationTime
Tuesday, June 14, 2022 5:17:14 PM
객체를 변수에 담아 두고 멤버 접근(.) 방식으로 속성을 가져올 수도 있어요. 아래 예시가 그 모습이에요.
$a = Get-ChildItem $PSHOME\pwsh.exe
$a.CreationTime
Wednesday, November 13, 2024 10:12:26 PM
Select-Object와 Format-List cmdlet을 써서 객체의 속성 값을 보여줄 수도 있어요. 두 cmdlet 모두 Property 매개 변수가 있는데, 여기에 하나 이상의 속성과 그 값을 지정할 수 있고, 와일드카드 문자(*)를 쓰면 모든 속성을 한 번에 나타낼 수 있어요.
예를 들어 아래 명령은 pwsh.exe 파일의 모든 속성 값을 보여줘요.
Get-ChildItem $PSHOME\pwsh.exe | Format-List -Property *
PSPath : Microsoft.PowerShell.Core\FileSystem::C:\Program Files\PowerShell\7-preview\pwsh.exe
PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Program Files\PowerShell\7-preview
PSChildName : pwsh.exe
PSDrive : C
PSProvider : Microsoft.PowerShell.Core\FileSystem
PSIsContainer : False
Mode : -a---
ModeWithoutHardLink : -a---
VersionInfo : File: C:\Program Files\PowerShell\7-preview\pwsh.exe
InternalName: pwsh.dll
OriginalFilename: pwsh.dll
FileVersion: 7.5.0.101
FileDescription: PowerShell 7
Product: PowerShell
ProductVersion: 7.5.0-rc.1 SHA: c0142dde17137e436e302b3c4e93e2d6dc50c5c4+c0142dde17137e436e302b3c4e93e2d6dc50c5c4
Debug: False
Patched: False
PreRelease: False
PrivateBuild: False
SpecialBuild: False
Language: Language Neutral
BaseName : pwsh
ResolvedTarget : C:\Program Files\PowerShell\7-preview\pwsh.exe
Target :
LinkType :
Name : pwsh.exe
Length : 284704
DirectoryName : C:\Program Files\PowerShell\7-preview
Directory : C:\Program Files\PowerShell\7-preview
IsReadOnly : False
Exists : True
FullName : C:\Program Files\PowerShell\7-preview\pwsh.exe
Extension : .exe
CreationTime : 11/13/2024 10:12:26 PM
CreationTimeUtc : 11/14/2024 4:12:26 AM
LastAccessTime : 1/3/2025 1:38:13 PM
LastAccessTimeUtc : 1/3/2025 7:38:13 PM
LastWriteTime : 11/13/2024 10:12:26 PM
LastWriteTimeUtc : 11/14/2024 4:12:26 AM
LinkTarget :
UnixFileMode : -1
Attributes : Archive
정적 속성(Static properties)
PowerShell에서는 .NET 클래스의 정적 속성도 사용할 수 있어요. 정적 속성은 객체의 속성이 아니라 클래스 자체의 속성이라는 점에서 일반 속성과 달라요.
클래스의 정적 속성을 가져오려면 Get-Member cmdlet의 Static 매개 변수를 쓰면 돼요. 예를 들어 아래 명령은 System.DateTime 클래스의 정적 속성을 가져와요.
Get-Date | Get-Member -MemberType Property -Static
TypeName: System.DateTime
Name MemberType Definition
---- ---------- ----------
MaxValue Property static datetime MaxValue {get;}
MinValue Property static datetime MinValue {get;}
Now Property datetime Now {get;}
Today Property datetime Today {get;}
UtcNow Property datetime UtcNow {get;}
정적 속성의 값을 가져올 때는 아래 문법을 사용해요.
[<ClassName>]::<Property>
예를 들어 아래 명령은 System.DateTime 클래스의 UtcNow 정적 속성 값을 가져와요.
[System.DateTime]::UtcNow
멤버 접근 열거(Member-access enumeration)
PowerShell 3.0부터, 존재하지 않는 속성에 멤버 접근 연산자(.)로 접근하면 PowerShell이 자동으로 컬렉션 안의 항목을 하나씩 열거하면서 각 항목의 해당 속성 값을 돌려줘요.
아래 명령은 Get-Service가 돌려준 모든 서비스의 DisplayName 속성 값을 반환해요.
(Get-Service).DisplayName
Application Experience
Application Layer Gateway Service
Windows All-User Install Agent
Application Identity
Application Information
...
PowerShell의 대부분의 컬렉션에는 컬렉션 안의 항목 수를 돌려주는 Count 속성이 있어요.
(Get-Service).Count
176
개별 객체에도 있고 컬렉션에도 있는 속성이라면, 컬렉션 쪽의 속성이 우선 반환돼요.
PS> $collection = @(
[pscustomobject]@{Length = "foo"}
[pscustomobject]@{Length = "bar"}
)
# PowerShell returns the collection's Length.
$collection.Length
2
# Get the Length property of each item in the collection.
PS> $collection.GetEnumerator().Length
foo
bar
더 자세한 내용은 about_Member-Access_Enumeration 문서에서 확인할 수 있어요.