Skip to content

Instantly share code, notes, and snippets.

@tomhawkin
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save tomhawkin/94efa1f139cdc8b00df3 to your computer and use it in GitHub Desktop.

Select an option

Save tomhawkin/94efa1f139cdc8b00df3 to your computer and use it in GitHub Desktop.
## Intro: Simple powershell script to install MongoDb as a service
## Note : These scripts require local admin priviliges!
$serviceName = "MongoDbTestService" #this is the name that windows uses to reference the service
$serviceDisplayName = "MongoDb - Test Service"
$port = "27017"
$projectName = "TestService"
$mongoDataDirectory = "C:\MongoDbData"
$mongodPath = "C:\MongoDB\bin"
$useAuth = $false
try {
#check if mongod exists
if ((Test-Path "$mongodPath\mongod.exe")) {
#check if the data directory exists and create if it doesnt
if (!(Test-Path $mongoDataDirectory)) {
"creating directory - $mongoDataDirectory"
mkdir "$mongoDataDirectory"
}
#check if the project directory exists and create if it doesnt
if (!(Test-Path "$mongoDataDirectory\$projectName")) {
"creating directory - $mongoDataDirectory\$projectName"
mkdir "$mongoDataDirectory\$projectName"
}
#check if the project db directory exists and create if it doesnt
if (!(Test-Path "$mongoDataDirectory\$projectName\db")) {
"creating directory - $mongoDataDirectory\$projectName\db"
mkdir "$mongoDataDirectory\$projectName\db"
}
#check if the project log directory exists and create if it doesnt
if (!(Test-Path "$mongoDataDirectory\$projectName\log")) {
"creating directory - $mongoDataDirectory\$projectName\log"
mkdir "$mongoDataDirectory\$projectName\log"
}
"Installing MongoDb Service"
#use auth if you are not in a trusted environment eg. if the server can be accessed by anyone
if($useAuth){
"using auth flag, the first user you create must be an admin user and you must connect from localhost"
& $mongodPath\mongod.exe --logpath "$mongoDataDirectory\$projectName\log\mongo.log" --serviceName $serviceName --serviceDisplayName $serviceDisplayName --port $port --dbpath "$mongoDataDirectory\$projectName\db" --auth --install
}
else{
& $mongodPath\mongod.exe --logpath "$mongoDataDirectory\$projectName\log\mongo.log" --serviceName $serviceName --serviceDisplayName $serviceDisplayName --port $port --dbpath "$mongoDataDirectory\$projectName\db" --install
}
#start service fails if run straight away, sleeping makes it work. if the service cant be started up this number or start manually from services
sleep 2
"Starting service"
Start-Service $serviceName
"Install complete. you can connect to this MongoDb instance at localhost:$port"
}
else{
"Please change the value of the mongodPath variable to your Mongo DB install path"
}
} catch {
"error!!"
throw
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment