PowerShell 配列への追加・要素変更Collections・固定配列

PowerShell

PowerShellで配列にデータ追加や要素変更をする必要がある場合。

# System.Collections.ArrayList
# System.Collections.Generic.List

$array = New-Object System.Collections.ArrayList
$array = New-Object System.Collections.Generic.List
$array.Add("test1")

# 追加(固定配列)
$array = @()
$array += "test1"

# 変更(共通)
$array[$i] += ",test2,test3"

使用例:


$array = New-Object System.Collections.ArrayList
# 追加
for ($i=0; $i -lt $count; $i++){
    # $null = $array.Add("test1")
    $array.Add("test1")
}


# 変更
for ($i=0; $i -lt $count; $i++){
    # $null = $array[$i] += ",test2,test3"
    $array[$i] += ",test2,test3"
}



$array = New-Object System.Collections.Generic.List[string]
# 追加
for ($i=0; $i -lt $count; $i++){
    # $null = $array.Add("test1")
    $array.Add("test1")
}

# 変更
for ($i=0; $i -lt $count; $i++){
    # $null = $array[$i] += ",test2,test3"
    $array[$i] += ",test2,test3"
}

# 固定配列(+=で追加)
$array = @()
    # 追加
for ($i=0; $i -lt $count; $i++){
    # $null = $array += "test1"
    $array += "test1"
}

# 変更
for ($i=0; $i -lt $count; $i++){
    # $null = $array[$i] += ",test2,test3"
    $array[$i] += ",test2,test3"
}

コメント