Public/Remove-ISCrawler.ps1

#requires -version 4


<#
.SYNOPSIS
    Removes a crawler configuration from an existing configuration file
.DESCRIPTION
    The Remove-ISCrawler cmdlet will remove a crawler configuration from an existing configuration file.
.EXAMPLE
    Get-ISCrawler .\CrawlerConfig.xml | ? {$_.InstanceId -eq "Test1"} | Remove-ISCrawler -Path .\CrawlerConfig.xml
.INPUTS
    Crawler, System.String
.OUTPUTS
    None
#>

function Remove-ISCrawler {
    [CmdletBinding(DefaultParameterSetName='Parameter Set 1',
                   SupportsShouldProcess=$true,
                   PositionalBinding=$false,
                   ConfirmImpact='Medium')]
    [Alias()]
    Param (
        # Crawler object to remove from the configuration file
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   ValueFromRemainingArguments=$false,
                   ParameterSetName='Parameter Set 1')]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [Alias()] 
        $Objects,
        
        # Path to the configuration file
        [Parameter(Mandatory=$true,
                   Position=0,
                   ParameterSetName='Parameter Set 1')]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [Alias("ConfigFile", "File", "FilePath")]
        [string] $Path
    )
    
    begin {
        $Path = Resolve-Path $Path       

        $xml = New-Object XML
        $xml.Load($Path)
        
        # Create XML namespaces for use when searching for the correct node to remove.
        # Prepend "ns:" to the node to search for
        $XmlNamespace = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
        $XmlNamespace.AddNamespace("ns", $xml.DocumentElement.NamespaceURI)
    }
    
    process {
        if ($pscmdlet.ShouldProcess("Target", "Operation")) {
            foreach ($Object in $Objects) {
                Write-Verbose "Processing crawler: $($Object.InstanceId)"
                $node = $xml.SelectSingleNode("//ns:Crawler[@InstanceId = '$($Object.InstanceId)']", $XmlNamespace)
                if ($node) {
                    [void]$node.ParentNode.RemoveChild($node)
                }
            }
        }
    }
    
    end {
        $xml = [xml] $xml.OuterXml.Replace(' xmlns=""', "")
        $xml.Save($Path)
    }
}