Public/Manufacturers.ps1

function Get-TMManufacturer {
    <#
    .SYNOPSIS
    Gets a Manufacturer from TransitionManager
 
    .DESCRIPTION
    This function will retrieve a Manufacturer from TransitionManager by name or Id
 
    .PARAMETER TMSession
    The name of the TM Session to use when retrieving a Manufacturer
 
    .PARAMETER Server
    The URI of the TransitionManager instance
 
.PARAMETER ResetIDs
    Switch indicating that the Manufacturer(s) should be returned without Id's
 
    .PARAMETER Page
    Used internally when more than 1000 Manufacturers exist in the TransitionManager instance
 
    .PARAMETER Name
    The name of the Manufacturer to be retrieved
 
    .PARAMETER Id
    The Id of the Manufacturer to be retrieved
 
    .EXAMPLE
    Get-TMManufacturer -TMSession 'TMDDEV2 -Name 'Acer'
 
    .OUTPUTS
    PSCustomObject representing the Manufacturer in TransitionManager
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [PSObject]$TMSession = 'Default',

        [Parameter(Mandatory = $false)]
        [Switch]$ResetIDs,

        [Parameter(Mandatory = $false)]
        [Int]$Page = 1,

        [Parameter(Mandatory = $false,
            Position = 0,
            ValueFromPipeline = $true,
            ParameterSetName = 'ByName')]
        [String]$Name,

        [Parameter(Mandatory = $true,
            Position = 0,
            ValueFromPipeline = $true,
            ParameterSetName = "ByAlias")]
        [String]$Alias,

        [Parameter(Mandatory = $true,
            ValueFromPipelineByPropertyName = $true,
            ParameterSetName = 'ById')]
        [Int[]]$Id
    )

    begin {

        ## Get Session Configuration
        $TMSession = Get-TMSession $TMSession

        # Format the request parameters
        $Instance = $TMSession.TMServer.Replace('/tdstm', '').Replace('https://', '').Replace('http://', '')
        $Uri = "https://$Instance/tdstm/manufacturer/listJson?rows=1000&page=$Page&sidx=name$(if ($Name) {"&name=$([System.Web.HttpUtility]::UrlEncode($Name))"})"
        Set-TMHeaderContentType -TMSession $TMSession -ContentType 'JSON'
        Set-TMHeaderAccept -TMSession $TMSession -Accept 'JSON'

        $WebRequestSplat = @{
            Method               = 'POST'
            Uri                  = $Uri
            WebSession           = $TMSession.TMWebSession
            SkipCertificateCheck = $TMSession.AllowInsecureSSL
        }

        # Make the request
        try {
            Write-Verbose "Web Request Parameters:"
            Write-Verbose ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            $Response = Invoke-WebRequest @WebRequestSplat
            Write-Verbose "Response status code: $($Response.StatusCode)"
            Write-Verbose "Response Content: $($Response.Content)"
        } catch {
            throw $_
        }

        # Process the server's response
        $Manufacturers = [System.Collections.ArrayList]::new()
        if ($Response.StatusCode -in 200, 204) {
            $Result = $Response.Content | ConvertFrom-Json -Depth 10

            [void]$Manufacturers.AddRange($Result.rows)

            # Continue to make calls until all pages have been recorded
            if ($Page -eq 1 -and $Result.total -gt 1) {
                for ($i = 2; $i -le $Result.total; $i++) {
                    [void]$Manufacturers.AddRange(
                        @(Get-TMManufacturer -TMSession $TMSession -Page $i)
                    )
                }
            }
        } else {
            throw "Unable to get Manufacturers"
        }
    }

    process {

        # Filter the results by the Name/Alias/Id passed in
        switch ($PSCmdlet.ParameterSetName) {
            'ByName' { $Manufacturers = $Manufacturers | Where-Object { $_.name -eq $Name } }
            'ById' { $Manufacturers = $Manufacturers | Where-Object { $_.id -in $Id } }
            'ByAlias' { $Manufacturers = $Manufacturers | Where-Object { $_.aliases.name -eq $Alias } }
        }

        # Remove the IDs if the ResetIDs switch was passed
        if ($ResetIDs) {
            for ($i = 0; $i -lt $Manufacturers.Count; $i++) {
                $Manufacturers[$i].id = $null
                for ($j = 0; $j -lt $Manufacturers[$i].aliases.Count; $j++) {
                    if ($Manufacturers[$i].aliases[$j].id) {
                        $Manufacturers[$i].aliases[$j].id = $null
                    }
                }
            }
        }

        $Manufacturers
    }
}


function New-TMManufacturer {
    <#
    .SYNOPSIS
    Creates a new Manufacturer in TransitionManager
 
    .DESCRIPTION
    This function will create a new Manufacturer in TransitionManager
 
    .PARAMETER TMSession
    The name of the TM Session to use when creating a Manufacturer
 
    .PARAMETER Server
    The URI of the TransitionManager instance
 
    .PARAMETER Name
    The name of the Manufacturer to be created
 
    .PARAMETER Description
    The new Manufacturer's description
 
    .PARAMETER CorporateName
    The corporate name of the new manufacturer
 
    .PARAMETER CorporateLocation
    The corporate loacation of the new manufacturer
 
    .PARAMETER Website
    The new manufacturer's website
 
    .PARAMETER Aliases
    One or more aliases for the new Manufacturer
 
    .PARAMETER InputObject
    A PSCustomObject representing the Manufacturer to be created
 
    .PARAMETER Passthru
    Switch indicating that the new Manufacturer should be returned after creation
 
    .EXAMPLE
    $NewManufacturerSplat = @{
        TMSession = 'TMDDEV'
        Name = 'NewCo'
        Description = 'This is a test manufacturer'
        CorporateName = 'NewCo, LLc'
        CorporateLocation = 'Houston, TX'
        Website = 'www.NewCo.com'
        Aliases = @('New Co', 'newco llc', 'new co inc')
        Passthru = $true
    }
    New-TMManufacturer @NewManufacturerSplat
 
    .EXAMPLE
    $ManufacturerFromTmddev = Get-TMManufacturer -TMSession 'TMDDEV' -Name 'Dell'
    New-TMManufacturer -TMSession 'TMDDEV2' -InputObject $ManufacturerFromTmddev
 
    .OUTPUTS
    If Passthru switch is used, an object representing the created Manufacturer. Otherwise, none
    #>


    param (
        [Parameter(Mandatory = $false)]
        [PSObject]$TMSession = 'Default',

        [Parameter(Mandatory = $true,
            ValueFromPipelineByPropertyName = $true,
            ParameterSetName = 'ByProperty')]
        [String]$Name,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            ParameterSetName = 'ByProperty')]
        [String]$Description,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            ParameterSetName = 'ByProperty')]
        [String]$CorporateName,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            ParameterSetName = 'ByProperty')]
        [String]$CorporateLocation,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            ParameterSetName = 'ByProperty')]
        [String]$Website,

        [Parameter(Mandatory = $false,
            ValueFromPipelineByPropertyName = $true,
            ParameterSetName = 'ByProperty')]
        [String[]]$Aliases,

        [Parameter(Mandatory = $true,
            ValueFromPipeline = $true,
            ParameterSetName = 'ByObject')]
        [PSCustomObject[]]$InputObject,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru
    )

    begin {

        if (!(Get-Module BAMCIS.Common)) {
            Import-Module BAMCIS.Common
        }

        ## Get Session Configuration
        $TMSession = Get-TMSession $TMSession

        # Format the request parameters
        $Instance = $TMSession.TMServer.Replace('/tdstm', '').Replace('https://', '').Replace('http://', '')
        $Uri = "https://$Instance/tdstm/manufacturer/save"
    }

    process {
        $ManufacturersToAdd = [System.Collections.ArrayList]::new()
        switch ($PSCmdlet.ParameterSetName) {
            'ByProperty' {
                [void]$ManufacturersToAdd.Add(
                    [PSCustomObject]@{
                        name              = $Name
                        description       = $Description
                        corporateName     = $CorporateName
                        corporateLocation = $CorporateLocation
                        website           = $Website
                        aliases           = $Aliases
                    }
                )
            }

            'ByObject' {
                $InputObject | ForEach-Object {
                    [void]$ManufacturersToAdd.Add(
                        [PSCustomObject]@{
                            name              = $_.Name
                            description       = $_.Description
                            corporateName     = $_.CorporateName
                            corporateLocation = $_.CorporateLocation
                            website           = $_.Website
                            aliases           = $_.Aliases
                        }
                    )
                }
            }
        }

        # Loop through the manufacturers and add them on the server
        foreach ($ManufacturerToAdd in $ManufacturersToAdd) {
            $ManufacturerCheck = Get-TMManufacturer -TMSession $TMSession -Name $ManufacturerToAdd.Name
            if (!$ManufacturerCheck) {
                $ManufacturerCheck = Get-TMManufacturer -TMSession $TMSession -Alias $ManufacturerToAdd.Name
            }

            if ($ManufacturerCheck) {
                if ($Passthru) {
                    $ManufacturerCheck
                }
                return
            }

            $WebRequestSplat = @{
                Method               = 'POST'
                Uri                  = $Uri
                WebSession           = $TMSession.TMWebSession
                SkipCertificateCheck = $AllowInsecureSSL
            }

            # Gather a list of aliases to add
            $AliasList = [System.Collections.ArrayList]::new()

            # Format the request body/form and header
            # Format the aliases property
            foreach ($Alias in $ManufacturerToAdd.aliases) {
                if ($Alias.GetType().ToString() -eq 'System.String') {
                    [void]$AliasList.Add(@{name = $Alias })
                } else {
                    [void]$AliasList.Add(@{name = $Alias.name })
                }
            }
            $ManufacturerToAdd.aliases = @{
                add    = $AliasList
                delete = @()
            }

            # Add the Manufacturer object as the body of the request
            $WebRequestSplat.Add('Body', ($ManufacturerToAdd | ConvertTo-Json -Depth 10))

            # Set the request Content-Type header
            Set-TMHeaderContentType -ContentType 'JSON' -TMSession $TMSession

            # Set the request Accept header
            Set-TMHeaderAccept -Accept 'Any' -TMSession $TMSession


            # Make the request
            try {
                Write-Verbose "Web Request Parameters:"
                Write-Verbose ($WebRequestSplat | ConvertTo-Json -Depth 10)
                Write-Verbose "Invoking web request"
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Verbose "Response status code: $($Response.StatusCode)"
                Write-Verbose "Response Content: $($Response.Content)"
            } catch {
                throw $_
            }

            if ($Response.StatusCode -in 200, 204) {
                if ($Passthru) {
                    Get-TMManufacturer -TMSession $TMSession -Name $ManufacturerToAdd.Name
                }
            } else {
                Write-Error "Manufacturer '$($ManufacturerToAdd.Name)' could not be created"
            }
        }
    }
}


function Remove-TMManufacturer {
    <#
    .SYNOPSIS
    Removes a Manufacturer from TransitionManager
 
    .DESCRIPTION
    This function will remove a Manufacturer in TransitionManager by Name or Id
 
    .PARAMETER TMSession
    The TransitionManager session to be used when deleting a Manufacturer
 
    .PARAMETER Server
    The URI of the TransitionManager instance
 
    .PARAMETER Name
    The name of the Manufacturer to be removed
 
    .PARAMETER Id
    The Id of the Manufacturer to be removed
 
    .EXAMPLE
    Remove-TMManufacturer -Name 'TestManufacturer' -TMSession 'TMDDEV'
 
    .EXAMPLE
    Remove-TMManufacturer -Id 154
 
    .EXAMPLE
    Remove-TMManufacturer -Name 'Acer'
 
    .OUTPUTS
    None
    #>


    param (
        [Parameter(Mandatory = $false)]
        [PSObject]$TMSession = 'Default',

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByName')]
        [String]$Name,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ById')]
        [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByName')]
        [String]$Id
    )

    begin {

        ## Get Session Configuration
        $TMSession = Get-TMSession $TMSession

        # Format the request parameters
        $Instance = $TMSession.TMServer.Replace('/tdstm', '').Replace('https://', '').Replace('http://', '')
        $Uri = "https://$Instance/tdstm/manufacturer/delete"

        Set-TMHeaderContentType -TMSession $TMSession -ContentType 'JSON'
        Set-TMHeaderAccept -TMSession $TMSession -Accept 'Any'
    }

    process {
        if (!$Id) {
            $Manufacturer = Get-TMManufacturer -TMSession $TMSession -Name $Name
            if (!$Manufacturer) {
                # Manufacturer doesn't exist
                return
            } else {
                $Id = $Manufacturer.id
            }
        }


        $WebRequestSplat = @{
            Method               = 'POST'
            Uri                  = $Uri + "/" + $Id
            WebSession           = $TMSession.TMWebSession
            SkipCertificateCheck = $TMSession.AllowInsecureSSL
            Body                 = (@{ id = $Id } | ConvertTo-Json)
        }

        # Make the request
        try {
            Write-Verbose "Web Request Parameters:"
            Write-Verbose ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            $Response = Invoke-WebRequest @WebRequestSplat
            Write-Verbose "Response status code: $($Response.StatusCode)"
            Write-Verbose "Response Content: $($Response.Content)"
        } catch {
            throw $_
        }

        if ($Response.StatusCode -notin 200, 204) {
            Write-Error "Manufacturer '$($ManufacturerToAdd.Name)' could not be removed"
        }
    }
}