PreMyProfileModuleProcess.ps1


# References:
# 1. Below are the list of predefined vars that can be used:
# - $PSScriptRoot [System defined] The folder path for current scipt file, NOT the caller script to call this function

<#
.SYNOPSIS
Invoke a script file in MyProfile module's caller scope.
 
.DESCRIPTION
Invoke a script file in MyProfile module's caller scope. Any exception is caught and print to host.
One major purpose of this function is to invoke script in MyProfile module's caller scope from MyProfile module scope.
 
.PARAMETER scriptPaths
The list of full path of the ps script file to run.
#>

function InvokeScriptInMyProfileModuleCallerScope
{
    param(
        [Parameter(Position=0, Mandatory=$true, ParameterSetName='ScriptPaths')]
        [string[]] $scriptPaths,

        [Parameter(Mandatory=$true, ParameterSetName='ScriptBlock')]
        [ScriptBlock] $scriptBlock
    )

    switch ($PsCmdlet.ParameterSetName)
    {
        "ScriptPaths"
        {
            $scriptPaths | % {
                $curScriptPath = $_
                if ((-NOT [string]::IsNullOrWhiteSpace($curScriptPath)) -AND (Test-Path $curScriptPath) -AND $curScriptPath.EndsWith('.ps1'))
                {
                    try {
                        . $curScriptPath | Out-Null
                    }
                    catch {
                        Write-Host "Failed to run script $curScriptPath in MyProfile module's caller scope." -ForegroundColor Red
                        Write-Host $_
                    }
                }
            }
        }

        "ScriptBlock"
        {
            try {
                . $scipt | Out-Null
            }
            catch {
                Write-Host "Failed to run script block in MyProfile module's caller scope." -ForegroundColor Red
                Write-Host $_
            }
        }
    }
}