Created
April 25, 2017 18:18
-
-
Save jmelosegui/3dcfc72cd315f6d54479435b70703226 to your computer and use it in GitHub Desktop.
Install npm in the UserProfile Folder if it does not exist.
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
[CmdletBinding()] | |
param( | |
[switch]$force | |
) | |
$userProfileDir = $env:USERPROFILE | |
$NodeDir = Join-Path $userProfileDir "Node" | |
if($force -and (Test-Path $NodeDir)){ | |
Remove-Item $NodeDir -Force -Recurse | |
} | |
$NodePath = Join-Path $NodeDir "Node.exe" | |
$NodeCommand = Get-Command $NodePath -ErrorAction SilentlyContinue | |
$NpmCommand = Get-Command "$NodeDir\npm.cmd" -ErrorAction SilentlyContinue | |
Function Get-ExternalTools { | |
if (!$NodeCommand) { | |
# External dependencies | |
$sourceNodeExe = "https://nodejs.org/download/release/latest/win-x64/node.exe" | |
Write-Output "Node.exe not found. Downloading to $NodePath..." | |
if (!(Test-Path $NodeDir -PathType Container)) { | |
New-Item -ItemType Directory -Force -Path $NodeDir | Out-Null | |
} | |
Invoke-WebRequest $sourceNodeExe -OutFile $NodePath | |
$script:NodeCommand = Get-Command $NodePath | |
} | |
if(!$NpmCommand){ | |
Write-Output "npm not found. Downloading to $NodePath..." | |
$npmBaseUrl = "http://nodejs.org/dist/npm/" | |
$npmZipFile = (Invoke-WebRequest $npmBaseUrl).Links | | |
Sort-Object { | |
[Version] $(if ($_.href -match "(\d+\.){3}zip") { | |
$matches[0] -replace “.zip$” | |
} | |
else { | |
"0.0.0.0" | |
}) | |
} -Descending | | |
Select -Property href -First 1 | |
$npmLatestVersion = "$npmBaseUrl$($npmZipFile.href)" | |
$npmZipPath = Join-Path $NodeDir $npmZipFile.href | |
Invoke-WebRequest $npmLatestVersion -OutFile $npmZipPath | |
Expand-Archive $npmZipPath -DestinationPath $NodeDir | |
$script:NpmCommand = Get-Command "$NodeDir\npm.cmd" | |
} | |
} | |
Get-ExternalTools | |
if(!($env:Path.Contains($NodeDir))){ | |
Write-Output "Adding the node dir to the path environment variable" | |
$env:Path += ";$NodeDir" | |
[Environment]::SetEnvironmentVariable( "Path", $env:Path, [System.EnvironmentVariableTarget]::User ) | |
} | |
if(!(Test-Path "$NodeDir\npm")) | |
{ | |
Write-Output "Installing npm" | |
& $NpmCommand install -g npm | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment