Public/Add-ISCrawler.ps1

#requires -version 4

function ModuleRoot { $PSScriptRoot | Split-Path -Parent}

<#
.SYNOPSIS
    Adds a crawler configuration to an existing configuration file
.DESCRIPTION
    The Add-ICDCrawlerToConfig cmdlet will add a valid crawler configuration to an existing configuration file.
.EXAMPLE
    New-ICDCrawler "FileConnector" "PublicFileShare" | Add-ICDCrawlerToConfig -Path "D:\IntelliSearch\ESP-1\Config\CrawlerConfig.xml"
.EXAMPLE
    Another example of how to use this cmdlet
.INPUTS
    Crawler, System.String
.OUTPUTS
    None
#>

function Add-ISCrawler {
    [CmdletBinding(DefaultParameterSetName='Parameter Set 1',
                   SupportsShouldProcess=$true,
                   PositionalBinding=$false,
                   ConfirmImpact='Medium')]
    [Alias()]
    Param (
        # Crawler objects to add to the configuration file
        [Parameter(Mandatory=$true,
                   Position=0,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   ValueFromRemainingArguments=$false, 
                   ParameterSetName='Parameter Set 1')]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [Alias()] 
        $Objects,
        
        # Path to the configuration file
        [Parameter(Mandatory=$true,
                   Position=1,
                   ParameterSetName='Parameter Set 1')]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [Alias("ConfigFile", "File", "FilePath")]
        [string] $Path
    )
    
    begin {
        $Path = (Resolve-Path $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)

        $Crawlers = $xml.SelectNodes("//ns:Crawlers", $XmlNamespace)
    }
    
    process {
        if ($pscmdlet.ShouldProcess("Target", "Operation")) {
            foreach ($Object in $Objects) {
                Write-Verbose "Processing node: $($Object.InstanceId)"
                $Imported = $xml.ImportNode($Object.ToXml().Crawler, $true)
                [Void] $Crawlers.AppendChild($Imported)
            }
        }
    }
    
    end {
        $xml = [xml] $xml.OuterXml.Replace(' xmlns=""', "")
        $xml.Save($Path)
    }
}