PSCUCM.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\PSCUCM.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName PSCUCM.Import.DoDotSource -Fallback $false
if ($PSCUCM_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName PSCUCM.Import.IndividualFiles -Fallback $false
if ($PSCUCM_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    if ($doDotSource) { . (Resolve-Path $Path) }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText((Resolve-Path $Path)))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\preimport.ps1"
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\postimport.ps1"
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
function Get-PhoneNameFromDN {
    <#
    .SYNOPSIS
    Get Phone Name based off of DN
     
    .DESCRIPTION
    Get Phone Name based off of DN
     
    .PARAMETER DN
    Directory Number to get phone for
     
    .PARAMETER AXLVersion
    Version of AXL
     
    .PARAMETER server
    Server to query
     
    .PARAMETER Credential
    Credential to use for API access
     
    .PARAMETER EnableException
    Replaces user friendly yellow warnings with bloody red exceptions of doom!
    Use this if you want the function to throw terminating errors you want to catch.
     
    .PARAMETER OutputXml
    Enable the output of the XML instead of the processing of the entity.
 
    .EXAMPLE
    Get-PhoneNameFromDN -DN 123 -Server 'CUCM-PUB.example.com' -Credential (Get-Credential)
 
    Get the Phone Name for Directory Number 123
    #>

    
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $DN,
        [Parameter(Mandatory = $true)]
        [string]
        $server,
        [string]
        $AXLVersion = '11.5',
        [Parameter(Mandatory = $true)]
        [pscredential]
        $Credential,
        [switch]
        $EnableException,
        [switch]
        $OutputXml
    )
    $CucmAxlSplat = @{
        SqlQuery        = @'
            SELECT device.name
            FROM
            device, numplan, devicenumplanmap
            WHERE
            devicenumplanmap.fkdevice = device.pkid
            AND
            devicenumplanmap.fknumplan = numplan.pkid
            AND
            numplan.dnorpattern = "{0}"
'@
 -f $DN
        server          = $server
        Credential      = $Credential
        AXLVersion      = $AXLVersion
        EnableException = $EnableException
        OutputXml       = $OutputXml
    }
    Invoke-CucmSql @CucmAxlSplat
}

function Add-Phone {
    <#
    .SYNOPSIS
    Add a Phone to CUCM Environment
     
    .DESCRIPTION
    Add a Phone to CUCM Environment
     
    .PARAMETER MacAddress
    MacAddress for the phone
     
    .PARAMETER Product
    Product
     
    .PARAMETER protocolSide
    Protocol Side (User?)
     
    .PARAMETER devicePoolName
    Name of DevicePool to put phone in.
     
    .PARAMETER commonPhoneConfigName
    Parameter description
     
    .PARAMETER phoneTemplateName
    Parameter description
     
    .PARAMETER Protocol
    Parameter description
     
    .PARAMETER AXLVersion
    Version of AXL
     
    .PARAMETER server
    Server to query
     
    .PARAMETER Credential
    Credential to use for API access
     
    .PARAMETER EnableException
    Replaces user friendly yellow warnings with bloody red exceptions of doom!
    Use this if you want the function to throw terminating errors you want to catch.
     
    .PARAMETER OutputXml
    Enable the output of the XML instead of the processing of the entity.
     
    .PARAMETER WhatIf
    What If?
     
    .PARAMETER Confirm
    Confirm...
     
    .EXAMPLE
    An example
     
    with more here...
     
    .NOTES
    General notes
    #>

    
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $MacAddress,
        [Parameter(Mandatory = $true)]
        [string]
        $Product,
        [Parameter(Mandatory = $true)]
        [string]
        $protocolSide,
        [Parameter(Mandatory = $true)]
        [string]
        $devicePoolName,
        [Parameter(Mandatory = $true)]
        [string]
        $commonPhoneConfigName,
        [Parameter(Mandatory = $true)]
        [string]
        $phoneTemplateName,
        [Parameter(Mandatory = $true)]
        [string]
        $Protocol,
        [string]
        $AXLVersion = '11.5',
        [Parameter(Mandatory = $true)]
        [string]
        $server,
        [Parameter(Mandatory = $true)]
        [pscredential]
        $Credential,
        [switch]
        $EnableException,
        [switch]
        $OutputXml
    )
    
    $class = 'Phone'
    $locationName = 'Hub_None'
    $useTrustedRelayPoint = 'Default'
    $primaryPhoneName = ''
    $deviceMobilityMode = 'Default'
    $certificateOperation = 'No Pending Operation'
    $packetCaptureMode = 'None'
    $builtInBridgeStatus = 'Default'
    
    $CucmAxlSplat = @{
        entity          = 'addPhone'
        # parameters = @{
        # phone = $phonexml
        # }
        parameters      = @{
            phone = @{
                name                  = $MacAddress
                product               = $Product
                class                 = $class
                protocol              = $Protocol
                protocolSide          = $protocolSide
                devicePoolName        = $devicePoolName
                commonPhoneConfigName = $commonPhoneConfigName
                locationName          = $locationName
                useTrustedRelayPoint  = $useTrustedRelayPoint
                phoneTemplateName     = $phoneTemplateName
                primaryPhoneName      = $primaryPhoneName
                deviceMobilityMode    = $deviceMobilityMode
                certificateOperation  = $certificateOperation
                packetCaptureMode     = $packetCaptureMode
                builtInBridgeStatus   = $builtInBridgeStatus
            }
        }
        server          = $server
        AXLVersion      = $AXLVersion
        Credential      = $Credential
        EnableException = $EnableException
        OutputXml       = $OutputXml
    }
        
    Invoke-CucmAxl @CucmAxlSplat
    
}


function Get-PhoneByDN {
    <#
    .SYNOPSIS
    Get the phone(s) based upon the DN
     
    .DESCRIPTION
    Get the phone(s) based upon the DN
     
    .PARAMETER DN
    Directory Number to lookup
     
    .PARAMETER AXLVersion
    Version of AXL
     
    .PARAMETER server
    Server to query
     
    .PARAMETER Credential
    Credential to use for API access
     
    .PARAMETER EnableException
    Replaces user friendly yellow warnings with bloody red exceptions of doom!
    Use this if you want the function to throw terminating errors you want to catch.
     
    .PARAMETER OutputXml
    Enable the output of the XML instead of the processing of the entity.
     
    .EXAMPLE
    Get-PhoneByDN -DN 123 -server 'Cucm-Pub.example.com' -Credential (Get-Credential)
 
    Get Phone with DN 123
    #>

    
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $DN,
        [Parameter(Mandatory = $true)]
        [string]
        $server,
        [Parameter(Mandatory = $true)]
        [pscredential]
        $Credential,
        [switch]
        $EnableException,
        [switch]
        $OutputXml
    )
    $phoneNameByDNSplat = @{
        DN              = $DN
        server          = $server
        Credential      = $Credential
        EnableException = $EnableException
        OutputXml       = $OutputXml
    }
    $phoneName = Get-PhoneNameFromDN @phoneNameByDNSplat |
        Select-Xml -XPath '//name' |
        Select-Object -ExpandProperty node |
        Select-Object -ExpandProperty '#text'
    $CucmAxlSplat = @{
        'server'     = $server
        'entity'     = 'getPhone'
        'parameters' = @{
            'name' = $phoneName
        }
        'Credential' = $Credential
    }
    Invoke-CucmAxl @CucmAxlSplat | Select-Xml -XPath '//phone' | Select-Object -ExpandProperty node
}

function Get-PhoneServicesByDN {
    <#
    .SYNOPSIS
    Get the services assigned to the phone based on the DN.
     
    .DESCRIPTION
    Get the services assigned to the phone based on the DN.
     
    .PARAMETER DN
    Directory Number to lookup
     
    .PARAMETER AXLVersion
    Version of AXL
     
    .PARAMETER server
    Server to query
     
    .PARAMETER Credential
    Credential to use for API access
     
    .PARAMETER EnableException
    Replaces user friendly yellow warnings with bloody red exceptions of doom!
    Use this if you want the function to throw terminating errors you want to catch.
     
    .PARAMETER OutputXml
    Enable the output of the XML instead of the processing of the entity.
     
    .EXAMPLE
    Get-PhoneServicesByDN -DN 123 -server 'Cucm-Pub.example.com' -Credential (Get-Credential)
 
    Get the Phone Services of phone with DN 123
    #>

    
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $DN,
        [Parameter(Mandatory = $true)]
        [string]
        $server,
        [Parameter(Mandatory = $true)]
        [pscredential]
        $Credential,
        [switch]
        $EnableException,
        [switch]
        $OutputXml
    )
    $PhoneByDNSplat = @{
        DN            = $DN
        server        = $server
        Credential    = $Credential
        EnableException = $EnableException
        OutputXml       = $OutputXml
    }
    Get-PhoneByDN @PhoneByDNSplat |
        Select-Xml -XPath '//service' |
        Select-Object -ExpandProperty node
}

function Invoke-CucmAxl {
    <#
    .SYNOPSIS
    Invoke AXL request against a CUCM server
     
    .DESCRIPTION
    Invoke AXL request against a CUCM server.
     
    .PARAMETER entity
    AXL entity to request
     
    .PARAMETER parameters
    Parameters for the AXL request
     
    .PARAMETER AXLVersion
    Version of AXL
     
    .PARAMETER server
    Server to query
     
    .PARAMETER Credential
    Credential to use for API access
     
    .PARAMETER EnableException
    Replaces user friendly yellow warnings with bloody red exceptions of doom!
    Use this if you want the function to throw terminating errors you want to catch.
     
    .PARAMETER OutputXml
    Enable the output of the XML instead of the processing of the entity.
     
    .EXAMPLE
    Invoke-CucmAxl -entity 'getPhone' -parameters @{ name = 'SEP000000000000' } -server 'Cucm-Pub.example.com' -Credential (Get-Credential)
     
    Invoke getPhone Entity with parameters...
    #>

    
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $entity,
        [Parameter(Mandatory = $true)]
        [hashtable]
        $parameters,
        [string]
        $AXLVersion = '11.5',
        [Parameter(Mandatory = $true)]
        [string]
        $server,
        [Parameter(Mandatory = $true)]
        [pscredential]
        $Credential,
        [switch]
        $EnableException,
        [switch]
        $OutputXml
    )
    $params = ''
    foreach ($paramKey in $parameters.Keys) {
        $inner = ''
        if ($parameters[$paramKey].GetType() -eq [System.Collections.Hashtable]) {
            $innerHash = $parameters[$paramKey]
            foreach ($innerKey in $innerHash.Keys) {
                $inner += '<{0}>{1}</{0}>' -f $innerKey, $innerHash[$innerKey]
            }
        }
        else {
            $inner = $parameters[$paramKey]
        }
        $params += '<{0}>{1}</{0}>' -f $paramKey, $inner
    }
    $body = @'
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.cisco.com/AXL/API/{0}">
        <soapenv:Header/>
        <soapenv:Body>
            <ns:{1}>
                {2}
            </ns:{1}>
        </soapenv:Body>
    </soapenv:Envelope>
'@
 -f $AXLVersion, $entity, $params
    
    if (-not $OutputXml) {
        if($PSCmdlet.ShouldProcess($server, "Execute AXL query $entity")) {
        
        $CUCMURL = "https://$server/axl/"
        $headers = @{
            'Content-Type' = 'text/xml; charset=utf-8'
        }
        $IRMParams = @{
            Headers    = $headers
            Body       = $body
            Uri        = $CUCMURL
            Method     = 'Post'
            Credential = $Credential
        }
        if ($PSVersionTable.PSVersion.Major -ge 6) {
            $IRMParams.SkipCertificateCheck = $true
        }
        else {
            [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
        }
        try {
            Invoke-WebRequest @IRMParams |
                Select-XML -XPath '//return' |
                Select-Object -ExpandProperty Node
        }
        catch {
            $ErrorMessage = $_.ErrorDetails.message
            $PSFMessage = "Failed to execute AXL entity $entity."
            if (($null -ne $ErrorMessage) -and ($_.Exception.Response.StatusCode -eq 'InternalServerError')) {
                $axlcode = ($ErrorMessage | select-xml -XPath '//axlcode' | Select-Object -ExpandProperty Node).'#text'
                $axlMessage = ($ErrorMessage | select-xml -XPath '//axlmessage' | Select-Object -ExpandProperty Node).'#text'
                $PSFMessage += " AXL Error: $axlMessage ($axlcode)"
            }
            Stop-PSFFunction -Message $PSFMessage -ErrorRecord $_ -EnableException $EnableException
            return
        }
        }
    }
    else {
        $body
    }
}


function Invoke-CucmSql {
    <#
    .SYNOPSIS
    Invoke a SQL Query against CUCM server using the AXL API
     
    .DESCRIPTION
    Invoke a SQL Query against CUCM server using the AXL API
     
    .PARAMETER SqlQuery
    SQL Query to be run
     
    .PARAMETER AXLVersion
    Version of AXL
     
    .PARAMETER server
    Server to query
     
    .PARAMETER Credential
    Credential to use for API access
     
    .PARAMETER EnableException
    Replaces user friendly yellow warnings with bloody red exceptions of doom!
    Use this if you want the function to throw terminating errors you want to catch.
     
    .PARAMETER OutputXml
    Enable the output of the XML instead of the processing of the entity.
     
    .EXAMPLE
    Invoke-CucmSql -SqlQuery 'select name from devices where name = "SEP000000000000"' -server 'Cucm-Pub.example.com' -Credential (Get-Credential)
 
    Invoke SQL Query against server...
    #>

    
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $SqlQuery,
        [string]
        $AXLVersion = '11.5',
        [Parameter(Mandatory = $true)]
        [string]
        $server,
        [Parameter(Mandatory = $true)]
        [pscredential]
        $Credential,
        [switch]
        $EnableException,
        [switch]
        $OutputXml
    )
    $CucmAxlSplat = @{
        server     = $server
        entity     = 'executeSQLQuery'
        parameters = @{
            sql = $SqlQuery
        }
        AXLVersion = $AXLVersion
        Credential = $Credential
        EnableException = $EnableException
        OutputXml       = $OutputXml
    }
    Invoke-CucmAxl @CucmAxlSplat
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'PSCUCM' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'PSCUCM' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'PSCUCM' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

<#
# Example:
Register-PSFTeppScriptblock -Name "PSCUCM.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name PSCUCM.alcohol
#>


New-PSFLicense -Product 'PSCUCM' -Manufacturer 'corbob' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2018-12-30") -Text @"
Copyright (c) 2018 corbob
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code