Public/Enable-Virtualenv.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Function Enable-Virtualenv {
    <#
    .SYNOPSIS
        To enable Virtualenv on your PowerShell console
    .PARAMETER Path
        Specifies the absolute path of your Virtualenv
    .EXAMPLE
        Enable-Virtualenv
        Enable-Virtualenv -Path 'c:\project\env'
    .NOTES
        Version: 1.0.0
        Author: Thomas ILLIET
        Creation Date: 22/07/2018
    #>

    [CmdletBinding(DefaultParameterSetName='ByName')]
    Param(
        [Parameter(Mandatory = $False, ParameterSetName = 'ByName')]
        [string]$Name,

        [Parameter(Mandatory = $False, ParameterSetName = 'ByPath')]
        [string]$Path
    )

    Try {
        # Define Virtualenv Path
        switch ($PsCmdlet.ParameterSetName){
            "ByName" {
                if([string]::IsNullOrEmpty($Name)){
                    $VirtualenvPath  = Join-Path -Path (get-location) -ChildPath 'venv'
                } else {
                    $VirtualenvPath  = Join-Path -Path (get-location) -ChildPath $Name
                }
            }
            "ByPath" {
                $VirtualenvPath  = $Path
            }
        }
        # Determine if the directory exists
        if(Test-Path -Path $VirtualenvPath) {
            # Get Folder Object
            $FolderObject = Get-Item -Path $VirtualenvPath

            # Set Variable to unlock function
            New-Variable -Scope 'Script' -Name 'VirtualenvFolder' -Value $FolderObject.FullName -Force
            New-Variable -Scope 'Script' -Name 'VirtualenvName' -Value $FolderObject.BaseName -Force

            # Overide Prompt
            Set-Item Function:\prompt -Value Set-Prompt
        } else {
            Write-Error "Unable to find Virtualenv directory"
        }
    } Catch {
        Write-Error "Unable to enable Virtualenv : $($_.Exception.Message)"
    }
}