Created
January 6, 2020 17:54
-
-
Save pldmgg/84210baef2d42958875f7550c5799080 to your computer and use it in GitHub Desktop.
Sets $env:PSModulePath Regardless of PS Version or Operating System
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Set-PSModulePath { | |
[CmdletBinding()] | |
Param () | |
[System.Collections.ArrayList]$ExpectedPaths = @() | |
# Handles Windows PowerShell | |
if (!$PSVersionTable.PSEdition -or $PSVersionTable.PSEdition -eq 'Desktop') { | |
$ExpectedModulePathA = [Environment]::GetFolderPath('MyDocuments') + "\WindowsPowerShell\Modules" | |
$ExpectedModulePathB = "C:\Windows\system32\WindowsPowerShell\v1.0\Modules" | |
$PathSep = ';' | |
} | |
# Handles PowerShell Core on Windows | |
if ($PSVersionTable.PSEdition -eq 'Core' -and $PSVersionTable.Platform -eq 'Win32NT') { | |
$ExpectedModulePathA = "C:\Program Files\PowerShell\Modules" | |
$ExpectedModulePathB = $(Get-Command pwsh).Source -replace 'pwsh\.exe','Modules' | |
$ExpectedModulePathC = [Environment]::GetFolderPath('MyDocuments') + "\PowerShell\Modules" | |
$PathSep = ';' | |
} | |
# Handles PowerShell Core on Linux | |
if ($IsLinux) { | |
$ExpectedModulePathA = "$HOME/.local/share/powershell/Modules" | |
$ExpectedModulePathB = $(Get-Command pwsh).Source -replace 'pwsh','Modules' | |
$ExpectedModulePathC = '/usr/local/share/powershell/Modules' | |
$PathSep = ':' | |
} | |
# Handles PowerShell Core on Mac | |
if ($IsMacOS) { | |
$ExpectedModulePathA = $(Get-Command pwsh).Source -replace 'pwsh','Modules' | |
$PathSep = ':' | |
} | |
$null = $ExpectedPaths.Add($ExpectedModulePathA) | |
$null = $ExpectedPaths.Add($ExpectedModulePathB) | |
$null = $ExpectedPaths.Add($ExpectedModulePathC) | |
# Since we potentially added some $null values above, we need to filter them out... | |
$UpdatedExpectedPaths = @($ExpectedPaths | Where-Object {$_ -ne $null}) | |
# Actually update $env:PSModulePath if necessary | |
$UpdatedExpectedPaths | foreach { | |
$ArrayOfPaths = $env:PSModulePath -split $PathSep | |
$PathExistsCheck = $ArrayOfPaths -contains $_ -or $ArrayOfPaths -contains $($_ + '\') -or $ArrayOfPaths -contains $($_ + '/') | |
if (!$PathExistsCheck) { | |
$env:PSModulePath = $_ + $PathSep + $env:PSModulePath | |
} | |
if (!$(Test-Path $_)) { | |
$null = New-Item -ItemType Directory $_ -Force | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment