You can use the following script to install NSSM and Azurite, as well as install Azurite as windows service. Of course, after some adjustments, it can also be used to run any powershell script snippet as windows service.
Usage:
- To install NSSM from Chocolatey and Azurite from NPM, use
script.ps1 install-dependencies
- To install Azurite as Service, use
script.ps1 install
- To uninstall the service, use
script.ps1 uninstall
# Can be used to run the Azurite Emulator as a Windows Service via NSSM
# Make sure to have NSSM installed (e.g. via "choco install nssm")
# Also make sure to have Azurite installed ("npm install -g azurite")
# You can also use the "install-dependencies" command
[cmdletbinding()]
param($command, $azuritePath)
# Service configuration
$serviceName = "AzuriteEmulator"
$serviceDisplayName = "Azurite Emulator as Windows Service"
$logsDirectory = "C:\azurite\logs"
# Setup of dynamic paths
$nssm = (Get-Command nssm).Source
$powershell = (Get-Command pwsh).Source
$scriptPath = $MyInvocation.MyCommand.Path
# Azurite-specific handling - we pass the Azurite path to the service so that it can be run under a different user account
if ($azuritePath -eq "" -Or $null -eq $azuritePath) {
$azuritePath = (Get-Command azurite).Source
}
$arguments = '-ExecutionPolicy Bypass -File "{0}" --command runservice -azuritePath "{1}"' -f $scriptPath, $azuritePath
if ($command -eq "runservice") {
# This is the script part we actually want to run inside the service
Write-Host ("Starting Azurite from '{0}'..." -f $azuritePath)
& $azuritePath --silent --location c:\azurite --debug c:\azurite\logs\azurite.log --loose
}
elseif ($command -eq "install") {
# Ensure logs directory exists
mkdir $logsDirectory -f
# Install service, set DisplayName and redirect outputs to logs
& $nssm install "$serviceName" "$powershell" "$arguments"
& $nssm set "$serviceName" DisplayName $serviceDisplayName
& $nssm set "$serviceName" AppStdout "$logsDirectory\service.log"
& $nssm set "$serviceName" AppStderr "$logsDirectory\service-error.log"
# Start service and print status
Start-Service $serviceName
Get-Service $serviceName
Write-Host "Installed and started Azurite as Windows Service" -f Green
}
elseif ($command -eq "uninstall") {
# Stop and then remove service
& $nssm stop $serviceName
& $nssm remove $serviceName confirm
Write-Host "Uninstalled Azurite as Windows Service" -f Green
}
elseif ($command -eq "install-dependencies") {
# Install nssm and azurite
Write-Host "Installing NSSM via Chocolatey..." -f Green
choco install nssm -y
Write-Host "Installing Azurite via NPM..." -f Green
npm install -g azurite
}
else {
Write-Host ("Unknown command '{0}'. Use 'install' or 'uninstall' from an elevated prompt." -f $command) -f Red
}