EnablePython.psm1

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
Set-StrictMode -Version 2.0

$OLD_ENV_PATH = $null

function Disable-Python {
<#
.SYNOPSIS
Disables any Python version enabled by the Enable-Python function.
 
.DESCRIPTION
The Disable-Python function restores the original PATH environment variable, removing any changes made by running the Enable-Python function.
 
It will also check for the existance of a 'deactivate' function, and it will call it if it exists (assuming that it is from the virtualenv activate.ps1' script).
#>


    [CmdletBinding()]

    param ()

    process {
        # test for a "deactivate" function, if it exists it probably means a virtualenv environment is in use
        # if so, call deactivate before restoring path
        if (
            ($deactivCmd = Get-Command "deactivate" -errorAction SilentlyContinue) -and
            ($deactivCmd.CommandType -eq "Function")
        ) {
            deactivate
        }

        if ($script:OLD_ENV_PATH) {
            # restore the original path
            $Env:PATH = $script:OLD_ENV_PATH
        }
    }
}

function Enable-Python {
<#
.SYNOPSIS
Adds an installed version of Python to the current shell environment.
 
.DESCRIPTION
The Enable-Python function adds the install path and scripts path for the specified Python version to the PATH
environment variable for this shell session. If multiple Python distributions are found, they are sorted in the
following order:
    - Scope (current user installs sorted first)
    - Company (alphabetical)
    - Version
    - Platform (descending)
    - Tag
The core Python distribution ("PythonCore") is treated as a special case and always sorted first. If multiple
versions are found, the top-sorted version is enabled.
 
.PARAMETER Company
The name of a company to filter Python distributions on.
 
.PARAMETER Tag
The tag value to filter Python distributions on.
 
.PARAMETER Version
The version number to filter Python distributions on.
 
.PARAMETER Platform
The underlying CPU architecture (either "32"-bit or "64"-bit) to filter Python distributions on.
 
.PARAMETER Scope
The operating system install scope (either "CurrentUser" or "AllUsers") to filter Python distributions on.
 
.EXAMPLE
Enable-Python
Gets all Python installs available, sorts them, and enables the top-most install (CurrentUser scope installs before
AllUser, PythonCore above others then alphabetical company name, highest version number, 64-bit before 32-bit).
 
.EXAMPLE
Enable-Python -Company ContinuumAnalytics
Gets all Python installs from Continuum Analytics, Inc., sorts them, and enables the top-most install (CurrentUser
scope installs before AllUser, highest version number, 64-bit before 32-bit).
 
.EXAMPLE
Enable-Python -Version 2.7 -Platform 32
Filters for 32-bit Python distributions with a version of 2.7.*, sorts them, and enables the top-most install
(CurrentUser scope installs before AllUser, PythonCore above others then alphabetical company name, highest version
number, 64-bit before 32-bit).
 
.EXAMPLE
Enable-Python 3.4 64
The Version and Platform parameters are positional, and can be specified without their respective names. Filters for
64-bit Python distributions with a version of 3.4.*, sorts them, and enables the top-most install (CurrentUser scope
installs before AllUser, PythonCore above others then alphabetical company name, highest version number, 64-bit before
32-bit).
 
.LINK
https://github.com/DavidWhittingham/ps-EnablePython
 
#>


    [CmdletBinding()]

    param (
        [Parameter()]
        [string]$Company,

        [Parameter()]
        [string]$Tag,

        [Parameter(Position = 1)]
        [string]$Version,

        [Parameter(Position = 2)]
        [ValidateSet(32, 64)]
        [Nullable[int]]$Platform,

        [Parameter()]
        [ValidateSet("CurrentUser", "AllUsers")]
        [string]$Scope
    )

    process {
        $getPythonArgs = @{
            "Company" = $Company;
            "Tag" = $Tag;
            "Version" = $Version;
        }
        if ($null -ne $Platform) {
            $getPythonArgs.Platform = $Platform
        }
        if  (![string]::IsNullOrWhiteSpace($Scope)) {
            $getPythonArgs.Scope = $Scope
        }

        [array]$pythons = Get-Python @getPythonArgs

        if (!$pythons) {
            throw "No Python distribution could be found matching those search criteria."
        }

        if ($pythons.Length -gt 1) {
            Write-Host "Multiple Python distributions found matching that criteria, enabling the top choice..."
        }

        # disable any existing Python version before enabling a new one
        Disable-Python

        $foundVersion = $pythons[0]

        # Save the existing path variable, then set the new path variable with the additional directories pre-pended.
        # Putting them at the start ensures the specified Python version will be the first one found (in case a Python
        # installation is already in the PATh variable).
        $script:OLD_ENV_PATH = $Env:PATH
        $Env:PATH = "$($foundVersion.InstallPath);$($foundVersion.ScriptsPath);$script:OLD_ENV_PATH"

        Write-Host """$($foundVersion.Name)"" has been enabled."
    }
}

function Get-Python {
<#
.SYNOPSIS
Gets the installed versions of Python on the current machine.
 
.DESCRIPTION
The Get-Python function finds Python installs on the current machine, collects their details and returns them as a
sorted list. Installs are sorted in the following order:
    - Scope (current user installs sorted first)
    - Company (alphabetical)
    - Version
    - Platform (descending)
    - Tag
The core Python distribution ("PythonCore") is treated as a special case and always sorted first.
 
.PARAMETER Company
The name of a company to filter Python distributions on.
 
.PARAMETER Tag
The tag value to filter Python distributions on.
 
.PARAMETER Version
The version number to filter Python distributions on.
 
.PARAMETER Platform
The underlying CPU architecture (either "32"-bit or "64"-bit) to filter Python distributions on.
 
.PARAMETER Scope
The operating system install scope (either "CurrentUser" or "AllUsers") to filter Python distributions on.
 
.EXAMPLE
Get-Python
Gets all Python installs available and sorts them.
 
.EXAMPLE
Get-Python -Company ContinuumAnalytics
Gets all Python installs from Continuum Analytics, Inc. and sorts them.
 
.EXAMPLE
Get-Python -Version 2.7 -Platform 32
Gets all 32-bit Python installs with a version of 2.7.* and sorts them.
 
.EXAMPLE
Get-Python 3.4 64
Gets all 364-bit Python installs with a version of 3.4.* and sorts them. The Version and Platform parameters are
positional, and can be specified without their respective names.
 
.LINK
https://github.com/DavidWhittingham/ps-EnablePython
 
#>


    [CmdletBinding()]
    [OutputType([PSObject])]

    param (
        [Parameter()]
        [string]$Company,

        [Parameter()]
        [string]$Tag,

        [Parameter(Position = 1)]
        [string]$Version,

        [Parameter(Position = 2)]
        [ValidateSet(32, 64)]
        [Nullable[int]]$Platform,

        [Parameter()]
        [ValidateSet("CurrentUser", "AllUsers")]
        [string]$Scope
    )

    <#
    .SYNOPSIS
    Lists the Python versions installed on this computer.
 
    #>


    process {
        $pythons = New-Object System.Collections.Generic.List[PSObject]

        $regKeyLocations = (
            @{
                path = "HKCU\Software\Python\"
                scope = "CurrentUser"
            },
            @{
                path = "HKLM\Software\Python\"
                scope = "AllUsers"
            }
        )

        if (is64Bit) {
            $regKeyLocations += @{
                path = "HKLM\SOFTWARE\Wow6432Node\Python\"
                scope = "AllUsers"
            }
        }

        foreach ($location in $regKeyLocations) {
            $companyKeys = Get-ChildItem -Path "Registry::$($location.path)" -ErrorAction "SilentlyContinue"

            foreach ($companyKey in $companyKeys) {

                if ($companyKey.PSChildName -eq "PyLauncher") {
                    # PyLauncher should be ignored
                    continue
                }

                $tagKeys = Get-ChildItem -Path $companyKey.PSPath -ErrorAction "SilentlyContinue"

                foreach($tagKey in $tagKeys) {
                    if (Test-Path (Join-Path $tagKey.PSPath "\InstallPath")) {
                        # tests if a valid install actually exists, uninstalled version can leave the Company/Tag structure
                        $pythons.Add((createPythonVersion $tagKey $location.scope))
                    }
                }
            }
        }

        # sort python core first
        $sortProperties = (
            @{
                Expression =" Scope";
                Descending = $true
            },
            @{
                Expression = "Company";
                Descending = $false
            },
            @{
                Expression = "Version";
                Descending = $true},
            @{
                Expression = "Platform";
                Descending = $true
            },
            @{
                Expression = "Tag";
                Descending = $false
            }
        )

        if (![string]::IsNullOrWhiteSpace($Scope)) {
            $pythons = ($pythons | Where-Object {"$($_.Scope)" -like "$Scope" })
        }

        if (![string]::IsNullOrWhiteSpace($Company)) {
            $pythons = ($pythons | Where-Object {"$($_.Company)" -like "$Company" + "*" })
        }

        if (![string]::IsNullOrWhiteSpace($Tag)) {
            $pythons = ($pythons | Where-Object {"$($_.Tag)" -like "$Tag" + "*" })
        }

        if (![string]::IsNullOrWhiteSpace($Version)) {
            $pythons = ($pythons | Where-Object {"$($_.Version)" -like "$Version*" })
        }

        if ($null -ne $Platform) {
            $pythons = ($pythons | Where-Object {"$($_.Platform)" -like "$Platform" })
        }

        @(
            @($pythons | Where-Object {$_.Company -eq "PythonCore"} | Sort-Object -Property $sortProperties) +
            @($pythons | Where-Object {$_.Company -ne "PythonCore"} | Sort-Object -Property $sortProperties)
        )
    }
}

function createPythonVersion([Microsoft.Win32.RegistryKey]$tagKey, [string]$scope) {
    $parentKey = Get-Item $tagKey.PSParentPath
    $installPathKey = Get-Item (Join-Path $tagKey.PSPath "InstallPath")
    $pythonExecutable = getPythonCommand $installPathKey
    $version = getPythonVersion($pythonExecutable)
    $company = $parentKey.PSChildName
    $companyDisplayName = if ((Get-ItemProperty -Path $parentKey.PSPath) -match "DisplayName") {
            (Get-ItemProperty -Path $parentKey.PSPath)."DisplayName"
        } else {
            $null
        }
    $tagDisplayName = if ((Get-ItemProperty -Path $tagKey.PSPath) -match "DisplayName") {
        (Get-ItemProperty -Path $tagKey.PSPath)."DisplayName"
    } else {
        $null
    }

    # Create a new PSObject for storing Python version information
    $obj = New-Object -TypeName PSObject -Prop (@{
        "Company"=$company;
        "CompanyDisplayName"=$companyDisplayName;
        "Tag"=$tagKey.PSChildName;
        "TagDisplayName"=$tagDisplayName;
        "InstallPath"=(Get-ItemProperty -Path $installPathKey.PSPath)."(Default)";
        "Platform"=if ((is64Bit) -and !($tagKey -match "Wow6432Node")) {"64"} else {"32"};
        "Executable"=$pythonExecutable;
        "Version"=$version;
        "Scope"=$scope;
    })

    Add-Member -InputObject $obj -MemberType ScriptProperty -Name "Name" -Value {
        $company = if ($null -eq $this.CompanyDisplayName) { $this.Company } else { $this.CompanyDisplayName }
        $tag = if ($null -eq $this.TagDisplayName) { $this.Tag } else { $this.TagDisplayName }
        return ("{0} {1} (x86-{2})" -f $company, $tag, $this.Platform)
    }
    Add-Member -InputObject $obj -MemberType ScriptProperty -Name "ScriptsPath" -Value {
        return (Join-Path $this.InstallPath "Scripts")
    }

    $defaultProperties = @("Name", "Company", "Tag", "Version", "Platform", "Scope")
    $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet("DefaultDisplayPropertySet", [string[]]$defaultProperties)
    $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
    $obj | Add-Member MemberSet PSStandardMembers $PSStandardMembers

    $obj
}

function getPythonCommand([Microsoft.Win32.RegistryKey]$installPathKey) {
    # test for "ExecutablePath" folder
    if ((Get-ItemProperty -Path $installPathKey.PSPath) -match "ExecutablePath") {
        Get-Command (Get-ItemProperty -Path $installPathKey.PSPath)."ExecutablePath"
    } else {
        $pythonPath = Join-Path (Get-ItemProperty -Path $installPathKey.PSPath)."(Default)" "python.exe"
        if (Test-Path $pythonPath) {
            Get-Command $pythonPath
        } else {
            $null
        }
    }
}

function getPythonVersion([System.Management.Automation.ApplicationInfo]$executablePath) {
    if ($executablePath -eq $null) {
        $null
    } else {
        & $executablePath -c 'from sys import version_info; print(""{0}.{1}.{2}"".format(version_info[0], version_info[1], version_info[2]))'
    }
}

function is64Bit {
    # Check if this machine is 64-bit
    ((Get-WmiObject Win32_OperatingSystem).OSArchitecture -match '64-bit')
}

Export-ModuleMember "*-*"