Private/Remove-UserFromSidecar.ps1

function Remove-UserFromSidecar
{
    <#
    .SYNOPSIS
     Removes a directory from the specfied device given in Get-DeviceInfo.
 
     .DESCRIPTION
     Remove-UserFromSideCar sorts the directories using Sort-BusyLampFields. Then, it presents the user with a list of directories currently on the device. The user then chooses which directory to remove. The function then removes the directory from a sorted xml document containing the directories. It then correctly reindexes the directories. The function then calls Update-SideCar which removes the user from the sidecar in CUCM.
 
     .PARAMETER FileName
     The XML document which holds the infomation of the device to be updated. Created from the SOAP response given from the AXL API. Default is "C:\Users\$env:USERNAME\Desktop\phoneInfo.xml"
 
    #>

    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory= $true)] $FileName
     )

    BEGIN{}

    PROCESS
    {
       
        $FileContent = [xml](Get-Content $FileName)
        #Sort the directories first.
        ConvertTo-SortedSidecar $FileName

        $SortedFile = "C:\users\$env:USERNAME\Desktop\Sorted.xml"
        $sortedDoc = [xml](Get-Content $SortedFile)

        $UserToRemove = Read-Host "Which entry do you want to remove? Select the corresponding number"

        #Removing chosen directory.
        $Nodes = $SortedDoc.SelectNodes("//busyLampFields/busyLampField")
        foreach($node in $Nodes)
        {
            if($node.index -eq $UserToRemove)
            {
                [void]$node.ParentNode.RemoveChild($node)
            }
        }
        [void]$SortedDoc.save($SortedFile)

        #Remove old indecies from sorted XML
        $BLFIndecies = $SortedDoc.SelectNodes("//busyLampFields/busyLampField/index")
        foreach($BLFIndex in $BLFIndecies)  
        {
            $RemoveIndex = $SortedDoc.SelectSingleNode("//busyLampField/index")
            [void]$RemoveIndex.ParentNode.RemoveChild($RemoveIndex)

        }
        [void]$SortedDoc.save($SortedFile)

        #Create a new <index> element in sorted XML. In order for the SOAP request to render successful, the index must be specified.
        $UpdatedNodes = $SortedDoc.SelectNodes("//busyLampFields/busyLampField")
        $index = 1
        foreach($newNode in $UpdatedNodes)
        {   
            
            $NewIndexNode = $SortedDoc.CreateElement("index")
            $NewIndexText = $SortedDoc.CreateTextNode($index)
            [void]$NewIndexNode.AppendChild($newIndexText)
            [void]$NewNode.AppendChild($NewIndexNode)
            $index = $index + 1 
        }
        [void]$SortedDoc.save($SortedFile) 

        Write-verbose "Sending SOAP request to remove user from the sidecar" -Verbose
        Update-Sidecar $SortedDoc $DeviceName
    }#PROCESS

    END{}
}