function Read-PSCustomObject {
param (
[Parameter(Mandatory=$true)][string]$FilePath
)
if (-not (Test-Path -Path $FilePath)) {
Write-Error "File not found: $FilePath"
return $null
}
$jsonContent = Get-Content -Path $FilePath -Raw
$psCustomObject = $jsonContent | ConvertFrom-Json
return $psCustomObject
}
function Write-PSCustomObject {
param (
[Parameter(Mandatory=$true)][PSCustomObject]$InputObject,
[Parameter(Mandatory=$true)][string]$FilePath
)
$jsonContent = $InputObject | ConvertTo-Json -Depth 100
Set-Content -Path $FilePath -Value $jsonContent
}
# 多段階のPSCustomObjectを作成
$psCustomObject = [PSCustomObject]@{
Name = 'John Doe'
Age = 30
Address = @{
Street = '123 Main St'
City = 'New York'
State = 'NY'
Country = 'USA'
}
Hobbies = @('Reading', 'Hiking', 'Traveling')
}
# PSCustomObjectをJSON形式でファイルに保存
$filePath = 'PSCustomObject.json'
Write-PSCustomObject -InputObject $psCustomObject -FilePath $filePath
# 保存したファイルからPSCustomObjectを読み込む
$loadedPSCustomObject = Read-PSCustomObject -FilePath $filePath
Write-Output $loadedPSCustomObject
# 関数名: Process-CustomObject
# 説明: この関数は、入力としてpsCustomObjectを受け取り、そのプロパティを再帰的に処理します。
function Process-CustomObject {
# パラメータ定義
param (
# 入力として受け取るpsCustomObject
[pscustomobject]$InputObject,
# オプションのインデントレベル。デフォルトは0。
[int]$IndentLevel = 0
)
# インデント文字列を生成
$indentString = " " * ($IndentLevel * 4)
# 入力オブジェクトのプロパティを取得
$properties = $InputObject | Get-Member -MemberType Properties
# プロパティごとに処理
foreach ($property in $properties) {
# プロパティの値を取得
$value = $InputObject.($property.Name)
# 値がpsCustomObjectの場合、再帰的に処理
if ($value -is [pscustomobject]) {
Write-Host "$indentString$($property.Name):"
# 再帰的に関数を呼び出す
Process-CustomObject -InputObject $value -IndentLevel ($IndentLevel + 1)
}
else {
# 値を出力
Write-Host "$indentString$($property.Name): $value"
}
}
}
# サンプルのpsCustomObjectを作成
$sampleObject = [PSCustomObject]@{
Name = "Alice"
Age = 30
Address = [PSCustomObject]@{
Street = "123 Main St"
City = "New York"
State = "NY"
Country = "USA"
}
}
# 関数を呼び出して、サンプルオブジェクトを処理
Process-CustomObject -InputObject $sampleObject