I don't think there's an easy way to insert a property into an object in-place at a specific index, but here's a quick proof-of-concept I knocked out to create a new object based on the original...
It could do with some error handling and perhaps some parameter attributes to support the pipeline, but it basically works...
function Insert-NoteProperty
{
param(
[pscustomobject] $InputObject,
[string] $Name,
[object] $Value,
[int] $Index
)
$properties = @($InputObject.psobject.Properties);
$result = [ordered] @{};
# append the properties before the index
for( $i = 0; $i -lt $Index; $i++ )
{
$result.Add($properties[$i].Name, $properties[$i].Value);
}
# append the new property
$result.Add($Name, $Value);
# append the properties after the index
for( $i = $Index; $i -lt $properties.Length; $i++ )
{
$result.Add($properties[$i].Name, $properties[$i].Value);
}
return [pscustomobject] $result;
}
Example:
$original = [pscustomobject] [ordered] @{ "aaa"="bbb"; "ccc"="ddd" }
$original
# aaa ccc
# --- ---
# bbb ddd
$updated = Insert-NoteProperty `
-InputObject $original `
-Name "new" `
-Value "value" `
-Index 1;
$updated
# aaa new ccc
# --- --- ---
# bbb value ddd
You can use this with a csv file as follows:
$csv = @"
aaa,ccc
bbb,ddd
"@
$data = $csv | ConvertFrom-Csv;
$newdata = $data | foreach-object {
Insert-NoteProperty `
-InputObject $_ `
-Name "new" `
-Value "value" `
-Index 1
}
$newcsv = $newdata | ConvertTo-Csv
$newcsv
# "aaa","new","ccc"
# "bbb","value","ddd"