Powershell 変数情報を表示

変数情報を表示

# 変数情報を表示
function GetVarInfo {
    param (
        [Parameter(Mandatory=$true)]
        [object]$Variable
    )

    Write-Host "変数の情報:"
    Write-Host "-------------------------"
    
    # 変数の型を表示
    $type = $Variable.GetType()
    Write-Host "型: $($type.FullName)"
    
    # 変数の値を表示
    Write-Host "値: $Variable"
    
    # 変数がオブジェクトの場合、そのプロパティを表示
    if ($type -ne [string] -and $type -ne [int] -and $type -ne [bool] -and $type -ne [double]) {
        Write-Host "プロパティ:"
        $properties = $Variable | Get-Member -MemberType Properties
        foreach ($property in $properties) {
            $name = $property.Name
            $value = $Variable.$name
            Write-Host "  ${name}: ${value}"
        }
    }
    Write-Host
}

# 使用例:
$A = [PSCustomObject]@{Name="John"; Age=30}
GetVarInfo -Variable $A

$A = @('aaa','bbb')
GetVarInfo $A

$A = 'aaa'
GetVarInfo $A

$A = 111
GetVarInfo $A
■実行結果

変数の情報:
-------------------------
型: System.Management.Automation.PSCustomObject
値: @{Name=John; Age=30}
プロパティ:
  Age: 30
  Name: John

変数の情報:
-------------------------
型: System.Object[]
値: aaa bbb
プロパティ:
  Length: 2

変数の情報:
-------------------------
型: System.String
値: aaa

変数の情報:
-------------------------
型: System.Int32
値: 111