0

I have a function that recursively examines an XML object loaded from file. I can retrieve the node data just fine, but when I try to insert the object with user data using the .Insert method, I get the error:

Exception calling "Insert" with "2" argument(s): "Insertion index was out of range. Must be non-negative and less than or equal to size. Parameter name: index"

If I replace the object values with simple string test values, insert works as expected. However, I'm using an object for each pass of the loop, and building up a large object to output to a file. Here is the simplified excerpt:

# some dummy values #
$drives = "value1","value2"
[System.Collections.ArrayList]$DriveObject = @()
$DriveObject.Add("$drives") | Out-Null

# some dummy users #
$FilterUser = "User1","User2"
[System.Collections.ArrayList]$UserObject = @()
$UserObject.Add("$FilterUser") | Out-Null

# insert user object into drive object #
$DriveObject.Insert($DriveObject.LastIndexOf('value2'),$UserObject)

# output #
$DriveObject

1 Answer 1

3

When you call $DriveObject.Add("$drives"), the expression "$drives" creates a new string, so $DriveObject doesn't actually contain two separate values, it contains only a single string "value1 value2".

Use the AddRange() method to add multiple items to the ArrayList at a time:

# some dummy values #
$drives = "value1","value2"
[System.Collections.ArrayList]$DriveObject = @()
$DriveObject.AddRange($drives) | Out-Null

# some dummy users #
$FilterUser = "User1","User2"
[System.Collections.ArrayList]$UserObject = @()
$UserObject.AddRange($FilterUser) | Out-Null

# insert user object into drive object #
$DriveObject.Insert($DriveObject.LastIndexOf('value2'),$UserObject)

# output #
$DriveObject
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I also noticed that the double quotes around the value cause errors, which you removed in your modification. PowerShell syntax can be awkward! Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.