dev.core.utils.psm1


function New-DirectoryIfNotExist
{
    [CmdletBinding()]
    param ([Parameter(Mandatory=$true, Position=0)][string]$Path);

    if (Test-Path -Path $Path -PathType Container)
    {
        Get-Item -Path $Path;
    }
    else
    {
        New-Item -Path $Path -ItemType Directory -Force;
    }
}

function Import-ModuleIfNotExist
{
    [CmdletBinding()]
    param ([Parameter(Mandatory=$true, Position=0)][string]$Name, [switch]$Global);

    if (!(Get-Module -Name $Name))
    {
        if (!(Get-Module -Name $Name -ListAvailable))
        {
            Write-Verbose "Installing ${Name} module";
            Install-Module -Name $Name;
        }

        Import-Module -Name $Name -Global:$Global -DisableNameChecking;
    }
}

function Add-TypeIfNotExist
{
    [CmdletBinding()]
    param([string]$TypeName, [string]$TypeDefinition);

    if (-not ([System.Management.Automation.PSTypeName]$TypeName).Type)
    {
        Add-Type -TypeDefinition $TypeDefinition;
    }
}

function Reset-Module
{

    [CmdletBinding()]
    param ([Parameter(ValueFromPipelineByPropertyName=$true)][string[]]$Name);

    process
    {
        foreach ($ModuleName in $Name)
        {
            $Module = Get-Module -Name $ModuleName;
            if (!$Module) {
                throw "Module $ModuleName is not found.";
            }

            Write-Verbose "Removing module $ModuleName";
            Remove-Module -Name $ModuleName -Force;

            Write-Verbose "Importing $($Module.Path)";
            Import-Module $Module.Path -Global;
        }
    }
}

function Test-RunAsAdmin
{
    [OutType([bool])]
    [CmdletBinding()]
    param();

    try
    {
        $identity = [Security.Principal.WindowsIdentity]::GetCurrent();
        $principal = New-Object Security.Principal.WindowsPrincipal -ArgumentList $identity;

        return $principal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator);
    }
    catch
    {
        return $false;
    }
}

function Confirm-RunAsAdmin
{
    [CmdletBinding()]
    param([string]$Command);

    if (!(Test-RunAsAdmin))
    {
        throw "The ${Command} command must be executed with administrator privilege.";
    }
}

function Merge-HashTable {
    param(
        [hashtable] $Table,
        [hashtable] $With)

    if (!$Table)
    {
        return $With;
    }
    elseif (!$With)
    {
        return $Table;
    }
    else
    {
        $MergedTable = $Table.Clone();

        foreach ($key in $With.Keys) {
            $MergedTable[$key] = $With[$key];
        }

        return $MergedTable;
    }
}

Export-ModuleMember -Function New-DirectoryIfNotExist;
Export-ModuleMember -Function Import-ModuleIfNotExist;
Export-ModuleMember -Function Add-TypeIfNotExist;
Export-ModuleMember -Function Reset-Module;
Export-ModuleMember -Function Test-RunAsAdmin;
Export-ModuleMember -Function Confirm-RunAsAdmin;
Export-ModuleMember -Function Merge-HashTable;