2017-01-25 41 views
2

目前我對Powershell非常困惑,以及它如何處理數組/列表和PSObjects/CustomObjects。Powershell根據元素數量返回不同的數據類型

高級別:

我試圖導入CSV文件,並在特定行「佔位符」條目插入。這實際上工作正常。我唯一的問題是,如果CSV只包含1個元素(Line),Powershell會創建一個PsCustomObject。如果有多行,Powershell提供一個數組。

1元的`$ pConnectionsOnMpDevice

$pConnectionsOnMpDevice = ($pList | ?({$_.device -like "*$pDevice*"})) 
($pConnectionsOnMpDevice).getType() 

IsPublic IsSerial Name BaseType 
True True PsCustomObject[] System.Object 
$pConnectionsOnMpDevice

$pConnectionsOnMpDevice = ($pList | ?({$_.device -like "*$pDevice*"})) 
($pConnectionsOnMpDevice).getType() 

IsPublic IsSerial Name BaseType 
True True Object[] System.Array 

N元素最後我嘗試添加元素:

$pConnectionsOnMpDevice += $MpObject 

(我的一個第一個方法是(FYI):

#$pConnectionsOnMpDevice.Insert($index,$match) 

如果我嘗試添加$MpObject$pConnectionsOnMpDevice我獲得以下錯誤:

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 

我想這是作爲描述here

同樣的問題,我試圖通過投$pConnectionsOnMpDeviceArraylist

[System.Collections.ArrayList]::$pConnectionsOnMpDevice += $MpObject 

但仍然沒有成功。

有沒有人有建議如何添加元素?

回答

5

使用數組子表達式運算符(@())強制值表達式返回數組:

$pConnectionsOnMpDevice = @($pList | ?({$_.device -like "*$pDevice*"})) 

I tried to cast $pConnectionsOnMpDevice to an Arraylist by:

[System.Collections.ArrayList]::$pConnectionsOnMpDevice += $MpObject 

這不是一個演員,這是一個靜態調用 - PowerShell中會調用任何靜態方法或財產與"$pConnectionOnMpDevice"具有相同的名稱。

取出::,如果你想有一個轉換操作:

$array = 1,2,3 
$arraylist = [System.Collections.ArrayList]$array 
+0

馬蒂亞斯, 非常感謝你對你有所幫助。小小的變化,但成功:) – cwa