Private/helpers.ps1

function Set-RKEnvironmentVariablesFromObject {
    param ( [object]$obj, 
        [string]$parentName = "")

    foreach ($p in $obj.PSObject.Properties) {
        if ($p.Value.GetType().name -eq "PSCustomObject") {
            $parentName = $parentName + $p.Name + "_"
            Set-RKEnvironmentVariablesFromObject -obj $p.Value -parentName $parentName
        }
        else {
            $VarName = ($parentName + $p.Name.replace(".", "_")).ToUpper()
            [System.Environment]::SetEnvironmentVariable($VarName, $p.Value, [System.EnvironmentVariableTarget]::Process)
        }
    }
}

function Add-RKValueToHashTable {
    param (
        [Parameter(Mandatory = $true)]
        $HashTable,

        [Parameter(Mandatory = $true)]
        [string]
        $Key,

        [Parameter(Mandatory = $true)]
        $Value,

        [Parameter(ParameterSetName = "Array", Mandatory = $true)]
        [switch]
        $AsJsonArray,

        [Parameter(ParameterSetName = "Object", Mandatory = $true)]
        [switch]
        $AsJsonObject
    )

    if ($AsJsonArray.IsPresent) {
        if (-not $HashTable.ContainsKey($Key)) {
            $HashTable[$Key] = @()
        }
    
        $HashTable[$Key] += $Value
    }

    if ($AsJsonObject.IsPresent) {
        $HashTable[$Key] = $Value
    }

    Write-Output $HashTable
}

function Get-RKGitRepositoryRoot {
    "$(git rev-parse --show-toplevel)"
}

function New-RKTimestampGuid {
    param (
        [datetime]$DateTime = (Get-Date -AsUTC)
    )
    
    return "_$($DateTime.ToString('yyyyMMddHHmmss'))_$((New-Guid).Guid)"
}

function Resolve-RKTheoreticalPath {
    param (
        [OutputType([String])]

        [System.IO.FileInfo]
        $FileName
    )
    $FileName = Resolve-Path $FileName.FullName -ErrorAction SilentlyContinue -ErrorVariable resolvePathError | Select-Object Path -ExpandProperty Path

    if (-not($FileName)) {
        $FileName = $resolvePathError[0].TargetObject
    }

    return $FileName.FullName
}

function Get-RKAzAccessToken{
    param([string]$Resource)
    (Get-AzAccessToken -ResourceUrl $Resource).Token
}

function Format-RKAzureScope {
    [CmdletBinding()]
    param (
        [Parameter()]
        [string]
        $Scope,

        [switch]
        $AsHashTable
    )

    $Scope = $Scope.TrimStart('/')
    $Scope = $Scope.TrimEnd('/')

    $segments = $Scope -split '/'

    if ($AsHashTable){
        $hashtable = @{}

        1..$segments.count | ForEach-Object { if ($_ % 2 -eq 1 ) { $hashtable.Add($segments[$_ - 1], $segments[$_]) } }

        return $hashtable
    }
}

function Write-RKError($message) {
    <#
.Description
Write an error message to the Console Window without the stack trace.
#>

    [Console]::ForegroundColor = 'red'
    [Console]::Error.WriteLine($message)
    [Console]::ResetColor()
}