Currently I'm very confused with Powershell and how it handles Arrays/ArrayLists and PSObjects/CustomObjects.
High level:
I'm trying to Import a CSV file and inserting at specific lines "placeholder" entries. This is actually working fine. My only issue the moment is, in case the CSV contains only 1 Element (Line) Powershell Creates a PsCustomObject
. If there are multiple lines, Powershell delivers an Array.
1 Element in `$pConnectionsOnMpDevice
$pConnectionsOnMpDevice = ($pList | ?({$_.device -like "*$pDevice*"}))
($pConnectionsOnMpDevice).getType()
IsPublic IsSerial Name BaseType
True True PsCustomObject[] System.Object
n Element in $pConnectionsOnMpDevice
$pConnectionsOnMpDevice = ($pList | ?({$_.device -like "*$pDevice*"}))
($pConnectionsOnMpDevice).getType()
IsPublic IsSerial Name BaseType
True True Object[] System.Array
Finally I try to add an Element:
$pConnectionsOnMpDevice += $MpObject
(One of my first approaches was to use (FYI):
#$pConnectionsOnMpDevice.Insert($index,$match)
If I try to add $MpObject
to $pConnectionsOnMpDevice
I get following error:
Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
At C:\Scripts\PS_GenerateMPConfig\PS_GenerateMPConfig_06_f.ps1:90 char:13
+ $pConnectionsOnMpDevice += $MpObject
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
I assume it's the same issue as described here
I tried to cast $pConnectionsOnMpDevice
to an Arraylist
by:
[System.Collections.ArrayList]::$pConnectionsOnMpDevice += $MpObject
But still no success.
Does anyone has an advice how I can add an element?
Use the array subexpression operator ( @()
) to force a value expression to return an array:
$pConnectionsOnMpDevice = @($pList | ?({$_.device -like "*$pDevice*"}))
I tried to cast $pConnectionsOnMpDevice to an Arraylist by:
[System.Collections.ArrayList]::$pConnectionsOnMpDevice += $MpObject
That's not a cast, that's a static invocation - PowerShell will invoke whatever static method or property has the same name as "$pConnectionOnMpDevice"
.
Remove the ::
if you want a cast operation:
$array = 1,2,3
$arraylist = [System.Collections.ArrayList]$array
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.