program story

Powershell에서 개체 속성 인쇄

inputbox 2020. 8. 28. 07:24
반응형

Powershell에서 개체 속성 인쇄


대화 형 콘솔에서 작업 할 때 새 개체를 정의하고 다음과 같이 일부 속성 값을 할당하면 :

$obj = New-Object System.String
$obj | Add-Member NoteProperty SomeProperty "Test"

그런 다음 대화 형 창에 변수 이름을 입력하면 Powershell에서 개체 속성 및 값에 대한 요약을 제공합니다.

PS C:\demo> $obj
SomeProperty                                                                                                                                                                                  
------------                                                                                                                                                                                  
Test

나는 기본적으로 이것을하고 싶지만 스크립트의 함수 내에서. 이 함수는 개체를 만들고 몇 가지 속성 값을 설정하고 반환하기 전에 개체 값의 요약을 Powershell 창에 인쇄하고 싶습니다. 함수 내에서 Write-Host를 사용해 보았습니다.

Write-Host $obj

그러나 이것은 요약이 아닌 객체의 유형을 출력합니다.

System.Object

내 함수가 개체의 속성 값 요약을 Powershell 창에 출력하도록하려면 어떻게해야합니까?


이 시도:

Write-Host ($obj | Format-Table | Out-String)

또는

Write-Host ($obj | Format-List | Out-String)

이 문제에 대한 내 해결책은 $ () 하위 표현식 블록 을 사용하는 것 입니다.

Add-Type -Language CSharp @"
public class Thing{
    public string Name;
}
"@;

$x = New-Object Thing

$x.Name = "Bill"

Write-Output "My name is $($x.Name)"
Write-Output "This won't work right: $x.Name"

제공 :

My name is Bill
This won't work right: Thing.Name

Powershell에서 개체의 속성 및 값을 인쇄합니다. 아래 예제 는 저에게 잘 맞습니다.

$ pool = Get-Item "IIS : \ AppPools.NET v4.5"

$ 풀 | 회원 가입

   TypeName: Microsoft.IIs.PowerShell.Framework.ConfigurationElement#system.applicationHost/applicationPools#add

Name                        MemberType            Definition
----                        ----------            ----------
Recycle                     CodeMethod            void Recycle()
Start                       CodeMethod            void Start()
Stop                        CodeMethod            void Stop()
applicationPoolSid          CodeProperty          Microsoft.IIs.PowerShell.Framework.CodeProperty
state                       CodeProperty          Microsoft.IIs.PowerShell.Framework.CodeProperty
ClearLocalData              Method                void ClearLocalData()
Copy                        Method                void Copy(Microsoft.IIs.PowerShell.Framework.ConfigurationElement ...
Delete                      Method                void Delete()
...

$ 풀 | Select-Object -Property * # -Property를 생략 할 수 있습니다.

name                        : .NET v4.5
queueLength                 : 1000
autoStart                   : True
enable32BitAppOnWin64       : False
managedRuntimeVersion       : v4.0
managedRuntimeLoader        : webengine4.dll
enableConfigurationOverride : True
managedPipelineMode         : Integrated
CLRConfigFile               :
passAnonymousToken          : True
startMode                   : OnDemand
state                       : Started
applicationPoolSid          : S-1-5-82-271721585-897601226-2024613209-625570482-296978595
processModel                : Microsoft.IIs.PowerShell.Framework.ConfigurationElement
...

팁 # 1

Write-Host를 사용하지 마십시오.

팁 # 12

PowerShell cmdlet 또는 함수에서 정보를 출력하는 올바른 방법은 데이터가 포함 된 개체를 만든 다음 Write-Output을 사용하여 파이프 라인에 해당 개체를 쓰는 것입니다.

-Don Jones : PowerShell 마스터

이상적으로 스크립트는 개체 ( $obj = New-Object -TypeName psobject -Property @{'SomeProperty'='Test'})를 만든 다음 Write-Output $objects. 출력을 Format-Table.

PS C:\> Run-MyScript.ps1 | Format-Table

실제로 PowerShell PowerObjectandPipingShell을 호출해야합니다.


# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName

The below worked really good for me. I patched together all the above answers plus read about displaying object properties in the following link and came up with the below short read about printing objects

add the following text to a file named print_object.ps1:

$date = New-Object System.DateTime
Write-Output $date | Get-Member
Write-Output $date | Select-Object -Property *

open powershell command prompt, go to the directory where that file exists and type the following:

powershell -ExecutionPolicy ByPass -File is_port_in_use.ps1 -Elevated

Just substitute 'System.DateTime' with whatever object you wanted to print. If the object is null, nothing will print out.


Some general notes.


$obj | Select-Object $obj | Select-Object -Property *

The latter will show all non-intrinsic, non-compiler-generated properties. The former does not appear to (always) show all Property types (in my tests, it does appear to show the CodeProperty MemberType consistently though -- no guarantees here).


Some switches to be aware of for Get-Member

  • Get-Member does not get static members by default. You also cannot (directly) get them along with the non-static members. That is, using the switch causes only static members to be returned:

    PS Y:\Power> $obj | Get-Member -Static
    
       TypeName: System.IsFire.TurnUpProtocol
    
    Name        MemberType Definition
    ----        ---------- ----------
    Equals      Method     static bool Equals(System.Object objA, System.Object objB)
    ...
    
  • Use the -Force.

    The Get-Member command uses the Force parameter to add the intrinsic members and compiler-generated members of the objects to the display. Get-Member gets these members, but it hides them by default.

    PS Y:\Power> $obj | Get-Member -Static
    
       TypeName: System.IsFire.TurnUpProtocol
    
    Name          MemberType     Definition
    ----          ----------     ----------
    ...
    pstypenames   CodeProperty   System.Collections.ObjectModel.Collection...
    psadapted     MemberSet      psadapted {AccessRightType, AccessRuleType,...
    ...
    

Use ConvertTo-Json for depth and readable "serialization"

I do not necessary recommend saving objects using JSON (use Export-Clixml instead). However, you can get a more or less readable output from ConvertTo-Json, which also allows you to specify depth.

Note that not specifying Depth implies -Depth 2

PS Y:\Power> ConvertTo-Json $obj -Depth 1
{
    "AllowSystemOverload":  true,
    "AllowLifeToGetInTheWay":  false,
    "CantAnyMore": true,
    "LastResortOnly": true,
...

And if you aren't planning to read it you can -Compress it (i.e. strip whitespace)

PS Y:\Power> ConvertTo-Json $obj -Depth 420 -Compress

Use -InputObject if you can (and are willing)

99.9% of the time when using PowerShell: either the performance won't matter, or you don't care about the performance. However, it should be noted that avoiding the pipe when you don't need it can save some overhead and add some speed (piping, in general, is not super-efficient).

That is, if you all you have is a single $obj handy for printing (and aren't too lazy like me sometimes to type out -InputObject):

# select is aliased (hardcoded) to Select-Object
PS Y:\Power> select -Property * -InputObject $obj
# gm is aliased (hardcoded) to Get-Member
PS Y:\Power> gm -Force -InputObject $obj

Caveat for Get-Member -InputObject: If $obj is a collection (e.g. System.Object[]), You end up getting information about the collection object itself:

PS Y:\Power> gm -InputObject $obj,$obj2
   TypeName: System.Object[]

Name        MemberType            Definition
----        ----------            ----------
Count       AliasProperty         Count = Length
...

If you want to Get-Member for each TypeName in the collection (N.B. for each TypeName, not for each object--a collection of N objects with all the same TypeName will only print 1 table for that TypeName, not N tables for each object)......just stick with piping it in directly.

참고URL : https://stackoverflow.com/questions/15792650/printing-object-properties-in-powershell

반응형