1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AIが学習用関数をつくった

Posted at

概要

Show-ObjectPropsTable は、PowerShell のオブジェクトのプロパティとその値、型を 学習用にわかりやすく表形式で表示するユーティリティ関数です。
オブジェクトの中身を確認したいとき、指定したプロパティだけを表示したいとき、またはすべてのプロパティを俯瞰したいときに便利です。

主な特徴

オブジェクトの型情報とプロパティ一覧を表示

どんな型のオブジェクトか、何個のプロパティを持っているか、一目で確認できます。

プロパティ名・値・値の型を表形式で出力

表形式にすることで、どのプロパティがどの型で、どの値を持っているかを直感的に理解できます。

指定プロパティだけを表示することも可能

必要なプロパティだけ絞り込んで学習することができます。

function Show-ObjectPropsTable {
    param(
        [Parameter(Mandatory)]
        [object]$InputObject,

        [string[]]$Properties
    )

    $output = @()

    if ($Properties) {
        # 指定されたプロパティだけ出力
        foreach ($p in $Properties) {
            if ($InputObject.PSObject.Properties.Name -contains $p) {
                $value = $InputObject.$p
                $output += [PSCustomObject]@{
                    Property = $p
                    Value    = $value
                    Type     = if ($value) { $value.GetType().Name } else { "Null" }
                }
            } else {
                Write-Warning "Property '$p' は存在しません。"
            }
        }
    } else {
        # 指定なしなら全部出力
        foreach ($prop in $InputObject.PSObject.Properties) {
            $value = $prop.Value
            $output += [PSCustomObject]@{
                Property = $prop.Name
                Value    = $value
                Type     = if ($value) { $value.GetType().Name } else { "Null" }
            }
        }
    }

    # オブジェクトの基本情報をオブジェクトとして作成
    $info = [PSCustomObject]@{
        ObjectType      = $InputObject.GetType().Name
        PropertyCount   = $InputObject.PSObject.Properties.Count
        PropertyNames   = ($InputObject.PSObject.Properties.Name -join ", ")
    }

    # 表形式で出力
    $info | Format-Table -AutoSize
    $output | Format-Table -AutoSize
}

使用例

  1. 全プロパティを表示
$os = Get-CimInstance Win32_OperatingSystem
Show-ObjectPropsTable -InputObject $os
  1. 特定プロパティだけ表示
Show-ObjectPropsTable -InputObject $os -Properties Caption,Version,OSArchitecture
  1. 存在しないプロパティを指定した場合
Show-ObjectPropsTable -InputObject $os -Properties Foo,Caption

→ 警告が表示され、有効なプロパティだけ出力されます。

ポイント

PowerShell オブジェクトのプロパティアクセス方法($object.PropertyName)

PSObject.Properties で全プロパティを列挙する方法

表形式で型や値を確認することで、オブジェクト構造の理解が深まる

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?