New-FunctionFromPS1.psm1


<#
.SYNOPSIS
    Create a Global Function from a PS1 file
.DESCRIPTION
    Create a Global Function from a PS1 file
.NOTES
    Authors : Simon Godefroy - Simon.Godefroy@FocusedIT.co.uk
    Version : 1.0.1
    Date : 2022.05.07
        Update : 1.0.1
                    SG - 2022.05.07
                    Initial Publish
        Update : 1.0.0
                    SG - 2022.05.07
                    Initial Script
.LINK
    http://www.FocusedIT.co.uk
#>



function New-FunctionFromPS1{
    <#
    .SYNOPSIS
        Create a Global Function from a PS1 file
    .DESCRIPTION
        Create a Global Function from a PS1 file
    .EXMAPLE
        New-FunctionFromPS1 -Path .\Invoke-TestScript.ps1
        Create a Global Function "Invoke-TestScript" from the file ".\Invoke-TestScript.ps1"
    .NOTES
        Author : Simon Godefroy - Simon.Godefroy@FocusedIT.co.uk
        Version : 1.0.0
        Date : 2022.05.07
            Update : 1.0.0
                        SG - 2022.05.07
                        Initial Script
    .LINK
        http://www.FocusedIT.co.uk
    #>

    [CmdletBinding()]
    Param(
        [string]$Path ,
        [string]$Description,
        [switch]$Quiet,
        [string]$Alias
    )
    process{
        try{
            if($Path -notlike "*.ps1"){
                throw "File not PS1"
            }
        } catch {
            Write-Error $Error[0] -ErrorAction Stop
        }
        try{
            if(!(Test-Path $Path)){
                throw "File not found ($Path)"
            }
        } catch {
            Write-Error $Error[0] -ErrorAction Stop
        }
        
        $FileDetails = Get-Item $Path
        $CommandName = (($FileDetails.Name).SubString(0,$FileDetails.Name.LastIndexOf('.')))
        $CommandString = Get-Content $Path -Raw
        $CmdScriptBlock = [Scriptblock]::Create($CommandString)
        Set-Item Function:global:$CommandName -Value $CmdScriptBlock -Force
        if($Alias){
            Set-Alias $Alias $CommandName -Scope Global -Force
        }
        if(!($Quiet)){
        Write-Output $CommandName
            if($Description){
                Write-Output "($Description)"
            }
        }
    }
}