[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

$PackagesPath = 'C:\Packages'
$DestinationPath = 'C:\Program Files\nssm'

$InstallerUrl = 'https://nssm.cc/ci/nssm-2.24-103-gdee49fc.zip'

$ArchivePath = Join-Path -Path $PackagesPath -ChildPath ($InstallerUrl | Select-String -Pattern "(nssm-(?:\d\.?)+-\d.*\.zip)").Matches.Value

# Exit if the application is already installed
if (Test-Path $DestinationPath) { Write-Host 'NSSM is already installed.'; exit }

# Prep

# Create the $PackagesPath directory if it doesn't already exist
if (-not (Test-Path -PathType Container $PackagesPath)) { New-Item -ItemType Directory -Path $PackagesPath | Out-Null }

# Download

Write-Host "Downloading application..."
# Use Legacy WebClient for compatibility
(New-Object Net.WebClient).DownloadFile($InstallerUrl, $ArchivePath)

# Extract

$ExpandedPath = $ArchivePath -replace '.zip',''

Write-Host "Extracting application..."
Expand-Archive -Path $ArchivePath -DestinationPath $PackagesPath -Force
Write-Host "Application extracted to $ExpandedPath"

# Install

Write-Host "Installing application..."
if (-not (Test-Path -PathType Container $DestinationPath)) { New-Item -ItemType Directory -Path $DestinationPath | Out-Null }
Move-Item -Path "$ExpandedPath\*" -Destination $DestinationPath

# Add the DestinationPath to Path system environment variable
[Environment]::SetEnvironmentVariable("Path", $env:Path + ";$DestinationPath\win64\", [System.EnvironmentVariableTarget]::Machine)

# Clean up

Write-Host "Removing package download from '$ArchivePath'"
Remove-Item -Path $ArchivePath -Force
Remove-Item -Path $ExpandedPath -Recurse -Force