Util/Initialize-ToolKit.ps1

#InitializeToolKit
param(
[ValidateNotNullOrEmpty()]
$ToolkitName
)

function Write-ActivityRecord
{
    $JeaDir         = join-path $env:ProgramFiles 'Jea' 
    $JeaActivityDir = Join-Path $JeaDir 'Activity'
    $Logfile        = Join-Path $JeaActivityDir 'ActivityLog.csv'

    $WinRMInfo = winrm enum shell |select-string "ProcessID = $pid" -Context 5,0
    $winRMID   = (($WinRMInfo.Context.PreContext |Select-String 'ShellID = ').Line.trim() -split ' = ')[1]
    $record    = $pssenderInfo |
        Add-member -PassThru -MemberType NoteProperty -Name PID           -Value $PID |
        Add-member -PassThru -MemberType NoteProperty -Name RunSpaceID    -Value $ExecutionContext.host.Runspace.InstanceId | 
        Add-member -PassThru -MemberType NoteProperty -Name Datetime      -Value (Get-Date) |
        Add-member -PassThru -MemberType NoteProperty -Name Toolkit       -Value  ($ToolkitName -join ';') |
        Add-member -PassThru -MemberType NoteProperty -Name WinRMShellID  -Value $WinRMID

    
    if (Test-Path $logFile) { $record |Export-Csv $Logfile -Append }
    else                    { $record |Export-Csv $Logfile }
}

#region Show Message Of The Day (MOTD)
function Show-Motd
{
    $motd = (Join-Path $env:ProgramFiles 'Jea\motd.txt')
    if (test-path $motd)
    {
        Write-Host (Get-Content $motd -raw)
    }
    foreach ($t in $toolkitName)
    {
        $motd = (Join-Path $env:ProgramFiles "Jea\Motd\$t.txt")
        if (test-path $motd)
        {
            Write-Host (Get-Content $motd -raw)
        }
    }
}
#endregion

function Import-Toolkit
{
param($ToolkitName)
    foreach ($t in $ToolkitName)
    {
        $path = (Join-path $env:ProgramFiles "Jea\toolkit\$($t).psm1")
        if (test-path $path)
        {
            Import-Module $path -Force -DisableNameChecking
        }
        else
        {
            Write-Error "[ToolKit]$path NotFound"
        }
    }
}

function Approve-Command
{
param([string[]]$name)

    foreach ($n in $name)
    {
        $approvedCommand.$n = 1
    }
}

function Approve-RemoteSessionCommand
{
    $iss = [System.Management.Automation.Runspaces.InitialSessionState]::CreateRestricted('RemoteServer')
    foreach ($f in $iss.Commands.Where({$_.CommandType -eq 'Function'}))
    {
        Set-Content "function:\$($f.Name)" -Value $f.definition
        Approve-Command $f.name 
    }
}


function Approve-ExportedApplication
{
    $apps = @()
    foreach ($m in Get-Module)
    {
        foreach ($a in &$m{$ExportedApplications})
        {
            if ($a)
            {
                $apps += $(Get-command $a).Definition
            }
        }
    }
    $ExecutionContext.SessionState.Applications.Clear()
    foreach ($a in $apps)
    {
        $ExecutionContext.SessionState.Applications.Add($a)
    }
}

function Block-UnauthorizedCommands 
{
param(
[Parameter(Mandatory=$true, Position=0)]
[ValidateNotNullOrEmpty()]
$Module)

    Get-Command | % {
        $cmd = $_
        if ($approvedCommand.$($cmd.Name) )
        {
            # If a proxy for a command exists, we need to remove the name from the list
            # so that we can hide the underlying command
            $approvedCommand.Remove($($cmd.Name))
        }
        else
        {
            $cmd.Visibility = 'private'
        }
        
    }
    
    #Certain commands are particularly dangerous so make sure that they are not exposed.
    foreach ($c in 'Invoke-Expression','Import-module')
    {    (Get-Command $c).Visibility = 'Private'
    }
}


function Enable-CommandLogging
{
param($Module)
    Get-Module $Module | % {$_.LogPipelineExecutionDetails = $true}
}

$approvedCommand = @{}
Write-ActivityRecord
Show-motd
Import-Toolkit $ToolkitName
Enable-CommandLogging $ToolkitName
Approve-RemoteSessionCommand
Approve-Command -name `
    'whoami',
    'get-module', 
    'get-alias',
    'format-table', #Need Safe Versions of format*
    'format-list',
    'tabexpansion2'
Approve-Command -name $((Get-Module  $ToolkitName ).Exportedfunctions.Values.name)
Block-UnauthorizedCommands -Module $ToolkitName
Approve-ExportedApplication
$ExecutionContext.SessionState.Scripts.Clear()    
$global:PSModuleAutoloadingPreference = 'none'
$ExecutionContext.SessionState.LanguageMode='noLanguage'