sourcecode

PowerShell에서 사용되는 GetType, 변수 간 차이

codebag 2023. 4. 8. 08:27
반응형

PowerShell에서 사용되는 GetType, 변수 간 차이

변수 간의 차이점은 무엇입니까?$a그리고.$b?

$a = (Get-Date).DayOfWeek
$b = Get-Date | Select-Object DayOfWeek

확인하려고 했다

$a.GetType
$b.GetType

MemberType          : Method
OverloadDefinitions : {type GetType()}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : type GetType()
Name                : GetType
IsInstance          : True

MemberType          : Method
OverloadDefinitions : {type GetType()}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : type GetType()
Name                : GetType
IsInstance          : True

그러나 이들 변수의 출력은 달라 보이지만 차이가 없는 것으로 보입니다.

우선 GetType을 호출하기 위한 괄호가 없습니다.[DayOfWeek]의 GetType 메서드를 설명하는 MethodInfo가 표시됩니다.실제로 GetType을 호출하려면 다음 작업을 수행해야 합니다.

$a.GetType();
$b.GetType();

넌 그걸 봐야 해$a는 [DayOfWeek] 입니다.$b는 데이터 객체의 DayOfWeek 속성만 캡처하기 위해 Select-Object cmdlet에 의해 생성되는 커스텀개체입니다.따라서 DayOfWeek 속성만 있는 개체입니다.

C:\> $b.DayOfWeek -eq $a
True

Select-Object는 새 psobject를 만들고 요청한 속성을 복사합니다.이것은 GetType()을 사용하여 확인할 수 있습니다.

PS > $a.GetType().fullname
System.DayOfWeek

PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject

Select-Object는 지정된 속성만 포함하는 사용자 지정 PSObject를 반환합니다.단일 속성을 사용하더라도 실제 변수는 PSObject 내에 래핑됩니다.

대신 다음 작업을 수행합니다.

Get-Date | Select-Object -ExpandProperty DayOfWeek

다음과 같은 결과를 얻을 수 있습니다.

(Get-Date).DayOfWeek

차이점은 Get-Date가 여러 개체를 반환하는 경우 파이프라인 방식은 예를 들어 항목의 배열과 같이 상위 가상 방식보다 더 잘 작동한다는 것입니다.PowerShell v3에서는 이 기능이 변경되었습니다.(Get-ChildItem).FullPath는 예상대로 동작하며 전체 경로의 배열만 반환합니다.

언급URL : https://stackoverflow.com/questions/7634555/gettype-used-in-powershell-difference-between-variables

반응형