When working with arrays and PSObject
in PowerShell, there are several efficient methods for creating and managing array elements. Below are examples that highlight both the creation of arrays and the addition of elements in different ways.
To create an empty array in PowerShell, you have two main options:
-
Using
[System.Collections.ArrayList]
This method initializes anArrayList
, which allows you to use the.Add()
method to add elements directly without creating a new array each time. -
Using
@()
This syntax creates a standard PowerShell array. However, adding elements with+=
can be less efficient since+=
creates a new array each time it is used.
To add elements to array.
-
Using
+=
You can add elements to a PowerShell array with the+=
operator, which works with different types like strings, integers, and custom objects. However, note that this approach can impact performance, especially with large arrays, as+=
creates a new array with each addition. -
Using
.Add()
with[System.Collections.ArrayList]
If you are using[System.Collections.ArrayList]
, the.Add()
method can improve efficiency by adding elements directly, without reallocating the array. To prevent unwanted output in PowerShell, you can use[void]
or$null =
to suppress the output of operations, especially when adding elements to arrays or performing operations that return a value but don't need to display it.
$services = Get-Service | Select-Object -First 10 $running = @() $stopped = [System.Collections.ArrayList]::new() #[System.Collections.ArrayList]$stopped = @() foreach ($service in $services) { if ($service.Status -eq 'Running') { $running += [PSCustomObject]@{ Status = $service.Status Name = $service.Name DisplayName = $service.DisplayName } } else { [void]$stopped.Add([PSCustomObject]@{ Status = $service.Status Name = $service.Name DisplayName = $service.DisplayName }) } } $running[1] $stopped[3]
Below is the another way but creating an object first and then using add method.
$list = New-Object System.Collections.ArrayList #'System.Collections.Generic.List[PSCustomObject]' $list.Add([PSCustomObject]@{Name='Test1'; Value=1}) $list.Add([PSCustomObject]@{Name='Test2'; Value=2}) $listCreating a fixed-size array in PowerShell can be helpful when you know the exact number of elements needed. This approach can offer better memory management compared to a dynamically growing array. You can create a fixed-size array using
[Object[]]::new(<size>)
, where <size>
is the number of elements the array will hold. Using Indexing I can simply add items to the array.
$objectArray = [Object[]]::new(5) $objectArray[0] = [PSCustomObject]@{ id = 1; name = "column1"; data = "data1" } $objectArray[1] = [PSCustomObject]@{ id = 2; name = "column2"; data = "data2" } $objectArray[2] = [PSCustomObject]@{ id = 3; name = "column3"; data = "data3" } $objectArray[3] = [PSCustomObject]@{ id = 4; name = "column4"; data = "data4" } $objectArray[4] = [PSCustomObject]@{ id = 5; name = "column5"; data = "data5" } $objectArray
for
loop. This is particularly useful if you want to initialize the array with specific values or incrementally calculated values.
$arrayNumber = 5 $array = New-Object 'System.Object[]' $arrayNumber for ($i = 0; $i -lt $arrayNumber; $i++) { $array[$i] = New-Object PSCustomObject -Property @{ id = $i name = "column$i" data = "data$i" } } $array
[System.Array]
to create a fixed-size array of objects. When additional space is needed, a new array is initialized with the larger size, and the original array is added to it. Then, objects can be inserted using the SetValue()
method.
$arrayNumber = 5 $array = [System.Array]::CreateInstance([System.Object], $arrayNumber) for ($i = 0; $i -lt $arrayNumber; $i++) { $array.SetValue([PSCustomObject]@{ id = $i; name = "column$i"; data = "data$i" }, $i) } $array $newArraySize = $arrayNumber + 2 $newArray = [System.Array]::CreateInstance([System.Object], $newArraySize) $array.CopyTo($newArray, 0) $newArray.SetValue("New Item 1", $arrayNumber) $newArray.SetValue("New Item 2", $arrayNumber + 1) $newArray
Useful Articles
Get-PSRepository WARNING Unable to find module repositories
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send
Creating an internal PowerShell module repository
How to sign PowerShell ps1 scripts
PowerShell Convert MAC address to Link-local address IPv6
PowerShell fix repair The trust relationship between this workstation and the primary domain failed
Resovled issue with PowerShell - Trust relationship Rejoin computers in domain without restart
PowerShell Invoke-WebRequest The request was aborted Could not create SSL TLS secure channel
PowerShell Invoke-WebRequest The underlying connection was closed: Could not establish trust relationship for the SSL TLS secure channel.
Powershell Write-Eventlog The source name test does not exist on computer localhost
Powershell New-Object Retrieving the COM class factory for component with CLSID 80040154 Class not registered (Exception from HRESULT 0x80040154 (REGDB_E_CLASSNOTREG))