Types/OpenPackage.Part/Relate.ps1

<#
.SYNOPSIS
    Adds Relationships to a package part
.DESCRIPTION
    Simplifies adding relationships to a package part.

    All relationships are external.

    If a relationship type is not provided, will default to "unknown"

    If no id is provided, will default to the relationship type.

    If relations with that type already exists, will append a counter to the id.
#>

param(
# The relationship uri
[Parameter(Mandatory)]
[uri]$uri, 
# The relationship type.
# If this is not provided, will default to `unknown`
[string]$type,
# The relationship id
# If not provided, will default to the type.
# If any relationships of the type already exist, will append a counter to the id.
[string]$id
) 

# Return if we cannot have relationships.
if (-not $this.GetRelationships) { return }
if (-not $this.CreateRelationship) { return }
# Default the type to `unknown`
if (-not $type) { $type = 'unknown'}
# and default the `$id` to the `$type`.
if (-not $id) { $id = $type }

# Get our relations
$relations = @(
    foreach ($relation in $this.GetRelationships()) {
        if ($relation.RelationshipType -eq $type) {
            $relation
        }
    }
)

# If we have no relations,
if (-not $relations) {
    # hard relate.
    $this.CreateRelationship(
        $uri, 'External', $type, $id
    )
} else {
    # Otherwise, create another relationship of the same type.
    $this.CreateRelationship(
        $uri, 'External', $type, "$($id)$($relations.Count)"
    )
}