Skip to content

Instantly share code, notes, and snippets.

@pldmgg
Created January 6, 2020 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pldmgg/84210baef2d42958875f7550c5799080 to your computer and use it in GitHub Desktop.
Save pldmgg/84210baef2d42958875f7550c5799080 to your computer and use it in GitHub Desktop.
Sets $env:PSModulePath Regardless of PS Version or Operating System
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