From my very limited Powershell knowledge, I seem to be getting arrays if the node repeats in a file but not if there is only one instance. To solve the problem, I'm having to duplicate my code because $ECN.PartRevisionData.PartRevision[$Index].ID
works for one XML file and $ECN.PartRevisionData.PartRevision.ID
works for another one. Is there a way to always have a node as an array even if there is only one entry in it?
Asked
Active
Viewed 89 times
1

sodawillow
- 12,497
- 4
- 34
- 44

RickInGarland
- 93
- 1
- 8
-
2Possible duplicate of [How can I force Powershell to return an array when a call only returns one object?](https://stackoverflow.com/questions/11107428/how-can-i-force-powershell-to-return-an-array-when-a-call-only-returns-one-objec) – TessellatingHeckler Oct 02 '17 at 18:27
-
Enclosing a variable in `@()` always converts it to an array. For example if `$a=1` then `@($a)` is an array with one item with value 1. Of coarse this pattern could be used to wrap more complicated expressions. – Alex Sarafian Oct 03 '17 at 07:59
2 Answers
0
Pipe it to a foreach-object loop. This will treat no array as array[0] and normal arrays as arrays.
This will get you your desired effect. Every ID of a specific Part Revision
$ECN.PartRevisionData.PartRevision[$Index].ID | %{$_}
You can even do different scopes of information like this....It will get you every ID of every Part Revision
$ECN.PartRevisionData.PartRevision | %{$_.ID}
You could even go a step farther and do something like ...
$ECN.PartRevisionData.PartRevision | %{$_} | select id, name, location (whatever you want to bring back)

ArcSet
- 6,518
- 1
- 20
- 34
0
Just enclose the result in an new array:@($ECN.PartRevisionData.PartRevision)
.
If the source isn't an array is will return an array, if the source is already an array, the same array will be returned. It will not create an embedded array which you might expect. This is standard PowerShell behavior:
PS C:\> $a = "a"
PS C:\> $b = @($a)
PS C:\> Write-Host $b ($b -is [array]) $b.count
a True 1
PS C:\>
PS C:\> $a = @("a", "b")
PS C:\> $b = @($a)
PS C:\> Write-Host $b ($b -is [array]) $b.count
a b True 2

iRon
- 20,463
- 10
- 53
- 79