PwSh.Fw.Core.psm1

<#
 
    .SYNOPSIS
    Resource file to export useful functions to prettify output
 
    .DESCRIPTION
 
    .NOTES
        Author: Charles-Antoine Degennes <cadegenn@gmail.com>
        New-ModuleManifest api.psd1 -RootModule api.psm1 -ModuleVersion "0.0.1" -Author "Charles-Antoine Degennes <cadegenn@gmail.com>"
#>


$Script:NS = (get-item $PSCommandPath).basename

<#
    .SYNOPSIS
    Template function
 
    .DESCRIPTION
    Skeleton of a typical function
 
    .PARAMETER string
    a string
 
    .EXAMPLE
    New-TemplateFunction -string "a string"
 
#>

function New-TemplateFunction {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param (
        [Parameter(Mandatory,ValueFromPipeLine = $true)][string]$string
    )
    Begin {
        # eenter($MyInvocation.MyCommand)
    }

    Process {
        return $string
    }

    End {
        # eleave($MyInvocation.MyCommand)
    }
}

# function Get-PwShFwModuleInfos {
# [CmdletBinding()][OutputType([String])]Param (
# # [Parameter(Mandatory = $true, ValueFromPipeLine = $true)][string]$string
# )
# Begin {
# # eenter($Script:NS + '\' + $MyInvocation.MyCommand)
# }

# Process {
# Write-Output "PSCommandPath = $PSCommandPath"
# Write-Output "PSScriptRoot = $PSScriptRoot"
# }

# End {
# # eleave($Script:NS + '\' + $MyInvocation.MyCommand)
# }
# }

<#
    .SYNOPSIS
    Execute a DOS/Shell command.
 
    .DESCRIPTION
    Wrapper for executing a DOS/Shell command. It handle (not yet) logging, (not yet) simulating and (not yet) asking.
    Please use following syntax :
    $rc = Execute-Commande "commande.exe" "arguments"
    to catch return code. Otherwise it will be printed to stdout and its quite ugly.
 
    .PARAMETER exe
    full path to executable
 
    .PARAMETER args
    all arguments enclosed in double-quotes. You may have to escape inner quotes to handle args with special characters.
 
    .PARAMETER AsInt
    Return code will be an int instead of a boolean.
 
    .EXAMPLE
    $rc = Execute-Command "net" "use w: \\srv\share"
 
#>

function Execute-Command() {
    [CmdletBinding()]
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "", Justification="Execute-Command is a more intuitive verb for this function and does not conflict with default Invoke-Command cmdlet.")]
    param(
        [parameter(mandatory=$true, position=0)][string]$exe,
        [parameter(mandatory=$false, position=1, ValueFromRemainingArguments=$true)][string]$args,
        [switch]$AsInt
    )

    $cmd = Get-Command -Name "$exe"
    switch ($cmd.CommandType) {
        'Application' {
            $exe = "& '" + $exe + "'"
            break
        }
        'ExternalScript' {
            $exe = "& '" + $exe + "'"
            break
        }
        'Cmdlet' {

        }
        default {

        }
    }

    Write-MyDebug ($exe + " " + $args)
    # $rcFile = $([System.IO.Path]::GetTempPath() + [IO.Path]::DirectorySeparatorChar + "rc")
    $rcFile = $([System.IO.Path]::GetTempPath() + "rc")
    # edevel("rcFile = $rcFile")
    # try {
        # if ($Global:DEVEL) {
        # if ($AsInt) {
        # Invoke-Expression ("$exe $args; `$LastExitCode | Out-File '$rcFile'") | Foreach-Object { Write-Devel $_ }
        # } else {
        # Invoke-Expression ("$exe $args; `$? | Out-File '$rcFile'") | Foreach-Object { Write-Devel $_ }
        # }
        # #return $?
        # } elseif ($Global:DEBUG) {
        # if ($AsInt) {
        # Invoke-Expression ("$exe $args; `$LastExitCode | Out-File '$rcFile'") | Out-Null
        # } else {
        # Invoke-Expression ("$exe $args; `$? | Out-File '$rcFile'") | Out-Null
        # }
        # #return $?
        # } else {
        # if ($AsInt) {
        # Invoke-Expression ("$exe $args; `$LastExitCode | Out-File '$rcFile'") | Out-Null
        # } else {
        # Invoke-Expression ("$exe $args; `$? | Out-File '$rcFile'") | Out-Null
        # }
        # #return $?
        # }
        if ($AsInt) {
            $out = Invoke-Expression ("$exe $args; `$LastExitCode | Out-File '$rcFile'")
        } else {
            $out = Invoke-Expression ("$exe $args; `$? | Out-File '$rcFile'")
        }
        if ($Global:DEVEL) {
            $out | Foreach-Object { Write-Devel $_ }
        } elseif ($Global:DEBUG) {
            $out | Foreach-Object { Write-MyDebug $_ }
        }
        $rc = Get-Content "$rcFile" -Raw
        # # edevel("rc = $rc")
        # Remove-Item "$rcFile"
        # # edevel("return $rc")
        # # if ($null -ne $rc) {
            return $rc
        # } else {
        # return $false
        # }
    # return $true
    # } catch {
    # return $false
    # }
}

<#
    .SYNOPSIS
    Wrapper for Import-Module
 
    .DESCRIPTION
    It handle everything to not worry about error messages.
    * check if module exist in module path
    * if an absolute filename is given, check if module exist as well as manifest
    * load-it with an optional $Force parameter
    * write a warning if module cannot be found
 
    .PARAMETER Name
    Name of the module to load
 
    .PARAMETER FullyQualifiedName
    Absolute path and name of the module to load. It can be either the manifest file (.psd1) or the module file (.psm1)
 
    .PARAMETER Force
    Force a reload if module is already loaded
 
#>

function Load-Module {
    [CmdletBinding(
        DefaultParameterSetName="NAME"
    )]
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "", Justification="Load-Module is a more intuitive verb for this function and does not conflict with default Get-Module cmdlet.")]
    Param (
        [Parameter(ParameterSetName="NAME",Mandatory,ValueFromPipeLine = $true)]
        [string]$Name,
        [Parameter(ParameterSetName="FILENAME",Mandatory,ValueFromPipeLine = $true)]
        [string]$FullyQualifiedName,
        [switch]$Force,
        [ValidateSet('Required', 'Optional')]
        [string]$Policy = "Required"
    )
    Begin {
        # eenter($MyInvocation.MyCommand)
    }

    Process {
        switch ($PSCmdlet.ParameterSetName) {
            "NAME" {
                $module = Get-Module -ListAvailable $Name
                if ($null -eq $module) {
                    # fake module to display correct informations
                    # PowerShell < 5 does not return anything
                    $module = @{ name = $Name; path = $null}
                }
                break
            }
            "FILENAME" {
                $module = Get-Module -ListAvailable $FullyQualifiedName -ErrorAction Ignore
                if ($null -eq $module) {
                    # fake module to display correct informations
                    # PowerShell < 5 does not return anything
                    $module = @{ name = (Split-Path -Leaf $FullyQualifiedName); path = $FullyQualifiedName}
                }
                break
            }
        }

        # exit if module is already loaded
        $rc = Get-Module -Name $module.Name
        if ($null -ne $rc) {
            if ($Force -eq $false) {
                ebegin("Module $($module.name) already loaded...")
                eend $true
                return $true
            }
        }

        if ($Global:VERBOSE) {
            if ($Global:DEBUG) {
                ebegin("Importing module $($module.name) from '$($module.Path)'")
            } else {
                ebegin("Importing module $($module.name)")
            }
        }
        switch ($Policy) {
            'Required' {
                $ErrorAction = 'Ignore'
                # $ErrorAction = 'Continue'
            }
            'Optional' {
                $ErrorAction = 'Ignore'
            }
        }

        switch ($PSCmdlet.ParameterSetName) {
            "NAME" {
                Import-Module -Name $module.name -Global -Force:$Force -DisableNameChecking -ErrorAction $ErrorAction
                $rc = $?
                break
            }
            "FILENAME" {
                # -FullyQualifiedName is not supported in PS < 5
                if ($PSVersionTable.PSVersion.Major -lt 5) {
                    Import-Module $module.Path -Global -Force:$Force -DisableNameChecking -ErrorAction $ErrorAction
                } else {
                    Import-Module -FullyQualifiedName $module.Path -Global -Force:$Force -DisableNameChecking -ErrorAction $ErrorAction
                }
                $rc = $?
                break
            }
        }

        switch ($Policy) {
            'Required' {
                if ($rc -eq $false) {
                    efatal("Module $($module.name) was not found and policy is '$Policy'.")
                }
            }
            'Optional' {
            }
        }

        if ($Global:VERBOSE) {
            eend $rc
        }

        return $rc
    }

    End {
        # eleave($MyInvocation.MyCommand)
    }
}

<#
.SYNOPSIS
Test if a file exist
 
.DESCRIPTION
Long description
 
.EXAMPLE
An example
 
.NOTES
General notes
#>

function Test-FileExist {
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    Param (
        [Parameter(Mandatory,ValueFromPipeLine = $true)]
        [string]$Name
    )
    Begin {
        # eenter($MyInvocation.MyCommand)
    }

    Process {
        Test-Path $Name -PathType Leaf
    }

    End {
        # eleave($MyInvocation.MyCommand)
    }
}

<#
.SYNOPSIS
Test if a directory exist
 
.DESCRIPTION
Long description
 
.EXAMPLE
An example
 
.NOTES
General notes
#>

function Test-DirExist {
    [CmdletBinding()][OutputType([System.Boolean])]Param (
        [Parameter(Mandatory,ValueFromPipeLine = $true)]
        [string]$Path
    )
    Begin {
        # eenter($MyInvocation.MyCommand)
    }

    Process {
        Test-Path $Path -PathType Container
    }

    End {
        # eleave($MyInvocation.MyCommand)
    }
}

<#
    .SYNOPSIS
    Test if a registry property exist
 
    .DESCRIPTION
    There is not yet a builtin function to test existence of registry value. Thanks to Jonathan Medd, here it is.
 
    .PARAMETER RegPath
    Registry path to the key
 
    .EXAMPLE
    Test-RegKeyExist -RegPath HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion
 
    .NOTES
    General notes
 
    .LINK
    https://www.jonathanmedd.net/2014/02/testing-for-the-presence-of-a-registry-key-and-value.html
#>


function Test-RegKeyExist {
    param (
        [Alias('Path')]
        [parameter(Mandatory=$true)][ValidateNotNullOrEmpty()]$RegPath
    )

    Test-Path -Path $RegPath -PathType Container
}

<#
    .SYNOPSIS
    Test if a registry property exist
 
    .DESCRIPTION
    There is not yet a builtin function to test existence of registry value. Thanks to Jonathan Medd, here it is.
 
    .PARAMETER RegPath
    Registry path to the key
 
    .PARAMETER Name
    Name of the value to test
 
    .EXAMPLE
    Test-RegValueExist -RegPath HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Value ProgramFilesDir
 
    .NOTES
    General notes
 
    .LINK
    https://www.jonathanmedd.net/2014/02/testing-for-the-presence-of-a-registry-key-and-value.html
#>


function Test-RegValueExist {
    param (
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]$RegPath,
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]$Name
    )

    try {
        $rc = Get-ItemProperty -Path $RegPath | Select-Object -ExpandProperty $Name -ErrorAction Stop
        return $true
    } catch {
        return $false
    }
}

<#
    .SYNOPSIS
    Test if a variable exist
 
    .DESCRIPTION
    This function is silent and only return $true if the variable exist or $false otherwise.
 
    .PARAMETER Name
    a variable name to test
 
    .EXAMPLE
    Test-Variable -Name "myvar"
#>

function Test-Variable {
    [CmdletBinding()]Param (
        [Parameter(Mandatory,ValueFromPipeLine = $true)][string]$Name
    )
    Begin {
        # eenter($MyInvocation.MyCommand)
    }

    Process {
        Get-Variable -Name $Name -ErrorAction SilentlyContinue | Out-Null
        return $?
    }

    End {
        # eleave($MyInvocation.MyCommand)
    }
}

<#
    .SYNOPSIS
    Get a property value from a file
#>

function Get-PropertyValueFromFile {
    [CmdletBinding()]Param (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [string]$Filename,
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [string]$Propertyname
    )
    Begin {
        # eenter($MyInvocation.MyCommand)
    }

    Process {
        $value = (Get-Content $Filename -Raw | ConvertFrom-StringData).$Propertyname
        # trim quotes
        $value = $value -replace "'", "" -replace '"', ''
        return $value
    }

    End {
        # eleave($MyInvocation.MyCommand)
    }
}

<#
.SYNOPSIS
Add a custom path to the PSModulePath environment variable.
 
.DESCRIPTION
Add a custom path to the PSModulePath environment variable.
 
.PARAMETER Path
Path to add
 
.PARAMETER First
If specified, add the Path at the beginning of PSModulePath
 
.EXAMPLE
Add-PSModulePath -Path c:\MyProject\MyModules
 
.EXAMPLE
"C:\MyProject\MyModules" | Add-PSModulePath -First
 
.NOTES
General notes
#>

function Add-PSModulePath {
    [CmdletBinding()]Param (
        [Parameter(Mandatory,ValueFromPipeLine = $true)][string]$Path,
        [switch]$First
    )
    Begin {
        # eenter($Script:NS + '\' + $MyInvocation.MyCommand)
    }

    Process {
        try {
            if ($First) {
                $env:PSModulePath = $PATH + [IO.Path]::PathSeparator + $env:PSModulePath
            } else {
                $env:PSModulePath = $env:PSModulePath + [IO.Path]::PathSeparator + $PATH
            }
        } catch {
            ewarn($_.Exception.ItemName + ": " + $_.Exception.Message)
        }
        # edevel("env:PSModulePath = " + $env:PSModulePath)
    }

    End {
        # eleave($Script:NS + '\' + $MyInvocation.MyCommand)
    }
}

Set-Alias -Force -Name eexec        -Value Execute-Command
Set-Alias -Force -Name fileExist    -Value Test-FileExist
Set-Alias -Force -Name dirExist        -Value Test-DirExist
Set-Alias -Force -Name regKeyExist    -Value Test-RegKeyExist
Set-Alias -Force -Name regValueExist    -Value Test-RegValueExist
Set-Alias -Force -Name varExist        -Value Test-Variable

# Export-ModuleMember -Function * -Alias *