LoginSignup
15
21

More than 5 years have passed since last update.

PowerShellを使ってユーザー定義オブジェクトを作成

Last updated at Posted at 2016-06-30

環境

Windows PowerShell 2.0

コード

New-Object コマンドレットと -Property パラメータ を使用してユーザー定義オブジェクトを作成。

# 配列
$arr = @()

# ユーザー定義オブジェクトを追加
$p = @{index=-1; name=""; age=-1}
$arr += New-Object PSObject -Property $p
$arr += New-Object PSObject -Property $p
$arr += New-Object PSObject -Property $p

$arr[0].index = 0
$arr[0].name  = "あいうえお"
$arr[0].age   = 30

$arr[1].index = 1
$arr[1].name  = "かきくけこ"
$arr[1].age   = 18

$arr[2].index = 2
$arr[2].name  = "さしすせそ"
$arr[2].age   = 99


# こっちの方がいいかも
# ただし、index が inde とかになっていてもエラーにはならない
<#
$arr += New-Object PSObject -Property @{index=0; name="あいうえお"; age=30}
$arr += New-Object PSObject -Property @{index=1; name="かきくけこ"; age=18}
$arr += New-Object PSObject -Property @{index=2; name="さしすせそ"; age=99}
#>

# 表示
$arr

出力

name          age      index
----          ---      ----
あいうえお     30       0
かきくけこ     18       1
さしすせそ     99       2

Windows PowerShell 3.0以上であれば、

$c = [pscustomobject]@{index=1; name="あいうえお"; age=30}

のようにも記述できるらしい。

注意

文字列として展開したい場合、下記のようにすると失敗する。

# あいうえお と表示されてほしい
"$arr[0].name"
foreach ($a in $arr)
{
    "$a.name"
}

# 下記のように出力されてしまう
<#
  [0].name
@{name=あいうえお; age=30; index=0}.name
@{name=かきくけこ; age=18; index=1}.name
@{name=さしすせそ; age=99; index=2}.name
#>

属性を文字列に展開する場合、\$(\$arr[0].name) のように記述する必要がある。

"$($arr[0].name)"
foreach ($a in $arr)
{
    "$($a.name)"
}

# 出力
<#
あいうえお
あいうえお
かきくけこ
さしすせそ
#>

参考

【改訂新版】 Windows PowerShell ポケットリファレンス

15
21
3

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
15
21