Skip to content

Instantly share code, notes, and snippets.

@markcowl
Last active August 29, 2015 14:02
Show Gist options
  • Save markcowl/95324d3e68947dddf801 to your computer and use it in GitHub Desktop.
Save markcowl/95324d3e68947dddf801 to your computer and use it in GitHub Desktop.
Fix Windows Azure PowerShell PSModulePath (broken in 0.8.1, 0.8.2, 0.8.3)
In versions 0.8.1 - 0.8.3 of Windows Azure PowerShell, the installer prepended the value %PSModulePath% to the System environment variable for PSModulePath. This would cause some user-specific PowerShell scripts to be removed from the default path and to no longer be discoverable by default. The attached script fixes the issue. When run from an elevated command prompt it will clean up the machine-wide PSModulePath variable and the PSModulePath in the current session.
This is wrtten as a script. You must have ExecutionPolicy set to RemoteSigned or Unrestricted to run this script. It must be run from an elevated command prompt.
To execute, simply save the script to a ps1 file, like 'FixEnvironment.ps1' and run the script from the command line
> .\FixEnvironment.ps1
The script will prompt before making changes. You can control prompting using the standard parameters (e.g -Force)
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact="High")]
param([switch]$Force)
$stringToRemove = "%PSMODULEPATH%"
$machinePath = [System.Environment]::GetEnvironmentVariable("PSModulePath", "Machine")
$userPath = "$home\Documents\WindowsPowerShell\Modules"
if ($machinePath.StartsWith($stringToRemove))
{
$parts = $machinePath.Split(@(';'))
$uniquePaths = @{}
$newPath = ""
$parts | % {
if ((-not $uniquePaths.ContainsKey($_)) -and (-not [System.String]::Equals($stringToRemove, $_, `
[System.StringComparison]::OrdinalIgnoreCase)))
{
$uniquePaths.Add($_, "")
$newPath += $_ + ";"
}
}
if ($newPath.Length -gt 2)
{
$newPath = $newPath.Remove($newPath.Length - 1)
$localPath = $userPath + ";$newPath"
$oldLocalPath = $env:PSModulePath
if ($Force -or $PSCmdlet.ShouldProcess("Session", "Change local PSModule path from `'$oldLocalPath`' to `'$localPath`'"))
{
$env:PSModulePath = $localPath
Write-Output "Changed session PSModulePath from `'$oldLocalPath`' to `'$localPath`'"
}
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "To change the Machine-level PSModulePath, you must have Administrator rights. Please rerun this script as an Administrator"
Break
}
if ($Force -or $PSCmdlet.ShouldProcess("Machine", "Changing system PSModulePath from `'$machinePath`' to `'$newPath`'"))
{
[System.Environment]::SetEnvironmentVariable("PSModulePath", $newPath, "Machine")
Write-Output "Changed machine-wide PSModulePath from `'$machinePath`' to `'$newPath`'"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment