Removing an Element from an Array

PowerShell 0 Comments

In PowerShell, you can’t remove an element from an array even if the array object have a method remove, if you try to do it anyway, it will throw a NotSupportedException.

powershell remove element array

The solution is to use ArrayList.

Here is the scenario: suppose that you have a list of servers and you would like check something on them remotely, if they are online you do the check, if successful, you remove the server from the list, otherwise you keep checking all of those server until all of them return the expected result.

In my case, I was trying to get the status of the LCM (Local Configuration Manager) on a list of servers.So I constructed an ArrayList and then used the GetEnumerator() method to get an enumerator.
With this enumerator , I used:

  • MoveNext: to move to the next element.
  • Reset: to initialize the position to none.
  • Current: to get the current element.
  • Remove: to remove the unwanted element from the ArrayList

So the final script look like this:

[System.Collections.ArrayList]$Hosts = "server01", "server02", "server03", "server04"
# initilize the position
$myenu = $Hosts.GetEnumerator()
$myenu.MoveNext()

# setup the credentials for the remote server
$secpasswd = ConvertTo-SecureString "password" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("lab\admin", $secpasswd)

do {

    Write-Host "Testing if" $myenu.Current "is ready"
    if (Test-WSMan -ComputerName $myenu.Current -ErrorAction SilentlyContinue ) {
        
        Write-Host "Host" $myenu.Current "is online, checking installation status..."
        $Session = New-CimSession -ComputerName $myenu.Current -Credential $mycreds
        $LcmStatus = Get-DscLocalConfigurationManager -CimSession $Session | Select-Object LCMState
        if ($LcmStatus.LCMState -match "Idle") {
            Write-Host $myenu.Current "seems to be Idle, removing it from queue"
            $Hosts.Remove($myenu.Current)
            $myenu = $Hosts.GetEnumerator()
            $myenu.MoveNext()

        }else {
            # move to the next if it's not idle
            if ($myenu.MoveNext() -eq $false) {
                Write-Host "reset"
                $myenu.Reset()
                $myenu.MoveNext()
            }
        }

    }
    else {
        # test if we are at the end 
        if ($myenu.MoveNext() -eq $false) {
            Write-Host "reset"
            $myenu.Reset()
            $myenu.MoveNext()
        }

    }
    # Sleeping before starting the check again    
    Start-Sleep -s 10

}while ( $Hosts.Count -ne 0)

Write-Host "it seems that all hosts have finished their configuration"



1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.