How to create windows service to run a powershell script? - windows

I have infinite loop PowerShell (Testing purpose) script, which I want to run as a Service in Windows Server 2008 R2 (Standard).
I'm using the following command to create the Windows service,
sc.exe create "My PS1Service" binPath= "powershell.exe -NoLogo -Path D:\TEST\test.ps1"
And the result is [SC] CreateService SUCCESS
But when I try to run the service My PS1Service , it return the following error
Windows Could not srart the My PS1Service service on Local
Computer
Error 1053: The service did not respond to the start or control
request in a family
Any help here !!!

Due to the length of the articles I don't want to paste them in the answer.
Check out this post which is the most comprehensive source of info I've found regarding powershell services: https://msdn.microsoft.com/en-us/magazine/mt703436.aspx
which links to an example powershell service:
http://jf.larvoire.free.fr/progs/PSService.ps1
I didn't end up successfully modifying this as it was going to take me longer to read through it and understand it than it would to use a different method for my use case, but I'd certainly be going back to that if I needed to create a service in powershell in the future.
Also this: https://www.sapien.com/blog/2017/07/12/write-a-windows-service-in-powershell/

I've been looking all over the place for a decent way to make a PS1 into a service.
Easiest way I found is with Winsw:
https://github.com/kohsuke/winsw
Works like a charm.

I have had success with Non-sucking Service Manager (NSSM) as well. https://nssm.cc/

you can create by below step:
First go to the path where PowerShell script located.
Then run below Command:
powershell.exe -ExecutionPolicy UnRestricted -File .\filename.ps1

Related

How can I create a windows service from an exe created using Go?

I have a Go program where I am executing a command to run wmi exporter.
I have created an exe from this script using "go build".
exe works fine.
Now, I want to create a windows service for this exe.
I have tried sc.exe, I can see the service name in the service.misc but it throws an error if I try to start it.
To get arbitrary EXEs to run as a Windows Service, I've had good results using nssm

Azure xplat to run a CustomScriptExtension in a Windows VM

I am creating Windows VMs from the azure xplat cli, using the following command:
azure network vnet create --location "East US" testnet
azure vm create --vm-name xplattest3 --location "East US" --virtual-network-name testnet --rdp 3389 xplattest3 ad072bd3082149369c449ba5832401ae__Windows-Server-Remote-Desktop-Session-Host-on-Windows-Server-2012-R2-20150828-0350 username SAFEpassword!
After the Windows VM is created I would like to execute a powershell script to configure the server. As far I understand, this is done by executing a CustomScriptExtension.
I found several examples for PowerShell but no examples for Xplat cli.
I would like, for example, to run the following HelloWorld PowerShell script:
New-Item -ItemType directory -Path C:\HelloWorld
After reading documentation I should be able to run a CustomExtensionScript by executing something like this (the following command does not work):
azure vm extension set xplattest3 CustomScriptExtension Microsoft.Compute 1.4 -i '{"URI":["https://gist.githubusercontent.com/tk421/8b7dd37145eaa8f82e2f/raw/36c11aafd3f5d6b4af97aab9ef5303d80e8ab29b/azureCustomScriptExtensionTest"] }'
I think that the problem is the parameter -i. I have not been able to find an example on Internet. There are some references and documentation such as MSDN and Github, but no examples.
Therefore, my question: How to execute a PowerShell script after creating a Windows VM in Azure using the xplat cli ?
Please note that the my current approach is a CustomScriptExtension, but anything that allows to bootstrap a configuration script will be considered!
EDIT How do I know it is failing ?
After I run the command azure vm extension ...:
xplat cli confirms that the command has been executed properly.
As per MSDN documentation, the folder C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\ is created, but there is no script downloaded to C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\{version-number}\Downloads\{iteration}
The folder C:\HelloWorld is not created, which means that the contents of the script has not been executed.
I cannot find any sort of logs or a trace to know what happened. Does anyone knows where can I find this information ?
The parameters (The Json) that I used after reading the MSDN documentation were not correct. However, you can get clues of the correct parameters by reading the C# code.
And the final command is:
azure vm extension set xplattest3 CustomScriptExtension Microsoft.Compute 1.4 -i '{"fileUris":["https://macstoragetest.blob.core.windows.net/testcontainername/createFolder.ps1"], "commandToExecute": "powershell -ExecutionPolicy Unrestricted -file createFolder.ps1" }'
This command successfully creates the C:\HelloWorld directory.
NOTE: I decided to upload the script to Azure as I read in a post and in the documentation that is mandatory. However I just made a test to download the original script from Github and it is working fine, so I guess that the documentation is a bit outdated.
EDIT: I created an detailed article that explains how to provision windows servers with xplat-cli in Azure.

Powershell activedirectory web services

I am looking to have a webservice that makes a powershell call to add users to active directory. I have the PowerShell call but dont know how to make a webservice to issue the call. Below you will find the powershell script.
New-Item -Path <drive>:\RightsPolicyTemplate\<template_ID>\UserRight -Name <e-mail_address> [-FullControl] [-View] [-Edit] [-Save] [-Export] [-Print] [-Forward] [-Reply] [-ReplyAll] [-Extract] [-AllowMacros] [-ViewRightsData] [-EditRightsData] [-CustomRight <custom_right>,<custom_right>…]
I'm running windows 2008 R2.
You could implement a solution using PHP and HTML forms to call Powershell scripts to do the work. Please see my basic guide on getting started with this here: http://theboywonder.co.uk/2012/07/29/executing-powershell-using-php-and-iis/

Add nginx.exe as Windows system service (like Apache)?

I set up NGINX as a front end server for static content and I use Apache as a back-end server for other thing.
The thing is I can't find a logical answer that allows me to make nginx.exe a Windows system service (like my Apache).
Any come across an answer to this?
How to do it with Windows Service Wrapper
(Note: There are easier alternatives by now - see also solutions described here below using chocolatey package manager by suneg and using NSSM directly from Adamy)
Download the latest version of Windows Service Wrapper via github or nuget.
Current version as of this writing is v2.2.0
Since v2.x executables for .NET2.0 and .NET4.0 are available - others only on demand.
Rename winsw-*.exe to something like nginxservice.exe.
This is the name that will show up for the process that owns your nginx process.
Place an XML file next to the exe with the same base name, e.g. nginxservice.xml. The contents should be like below (verify your nginx location).
<service>
<id>nginx</id>
<name>nginx</name>
<description>nginx</description>
<executable>c:\nginx\nginx.exe</executable>
<logpath>c:\nginx\</logpath>
<logmode>roll</logmode>
<depend></depend>
<startargument>-p</startargument>
<startargument>c:\nginx</startargument>
<stopexecutable>c:\nginx\nginx.exe</stopexecutable>
<stopargument>-p</stopargument>
<stopargument>c:\nginx</stopargument>
<stopargument>-s</stopargument>
<stopargument>stop</stopargument>
</service>
You can find up to date details about the configuration on the config github page, a generic example showing all possible options here and an installation guide.
Run the command nginxservice.exe install as administrator.
You will now have an nginx service in your Services! (It is set to start automatically on boot; if you want to start your server, you must manually start the service (net start nginx).)
Detailed description of correctly setting up nginx as a Windows Service:
http://web.archive.org/web/20150819035021/http://misterdai.yougeezer.co.uk/posts/2009/10/16/nginx-windows-service/
Additional info not contained in above blog post:
You can find the latest version of the Windows Service Wrapper also via this Maven Repository:
http://repo.jenkins-ci.org
Examples for Maven + Gradle:
<dependency>
<groupId>com.sun.winsw</groupId>
<artifactId>winsw</artifactId>
<version>2.2.0</version>
<classifier>bin</classifier>
<packaging>exe</packaging>
</dependency>
<repository>
<id>jenkinsci</id>
<name>jenkinsci-releases</name>
<url>http://repo.jenkins-ci.org/releases</url>
</repository>
compile "com.sun.winsw:winsw:2.2.0"
repositories {
mavenCentral()
maven { url http://repo.jenkins-ci.org/releases }
}
Download NSSM form
http://nssm.cc/download .
"Run %NSSM_HOME%\nssm.exe install “Nginx”"
Select the Nginx executable in the NSSM dialog, then OK.
Go to Services and start the new created service "Nginx", done.
You can using start.bat and stop.bat to realize the same effect.
start.bat
#ECHO OFF
REM Start Nginx
tasklist /FI "IMAGENAME eq nginx.exe" 2>NUL | find /I /N "nginx.exe">NUL
IF NOT "%ERRORLEVEL%"=="0" (
REM Nginx is NOT running, so start it
c:
cd \nginx
start nginx.exe
ECHO Nginx started.
) else (
ECHO Nginx is already running.
)
stop.bat
#ECHO OFF
REM Stop Nginx
tasklist /FI "IMAGENAME eq nginx.exe" 2>NUL | find /I /N "nginx.exe">NUL
IF "%ERRORLEVEL%"=="0" (
REM Nginx is currently running, so quit it
c:
cd \nginx
nginx.exe -s quit
ECHO Nginx quit issued.
) else (
ECHO Nginx is not currently running.
)
SC.EXE will only work for executables that already support the Windows Services API and can respond properly to start and stop requests from the Services Control Manager (SCM). Other regular applications, not specifically written as a service, will simply fail to start (usually with error 1053)...
For those exe's, you need a "service wrapper" -- a small utility that can accept the start/stop commands from the SCM and run/terminate your application accordingly. Microsoft provides Srvany (which is free yet very basic), but there are several other free and commercial alternatives.
BTW, you should check out this guide showing how to run Nginix as a service, especially step 7 which discusses how to stop Nginix properly. Not every wrapper will support that functionality (Srvany doesn't)...
The easiest way I've found, was using the Chocolatey package manager.
Once Chocolatey is installed, you open an administrative prompt and type:
choco install nginx
You now have a Windows service named 'nginx' running.
NSSM is the best tool to run Nginx as a service.
If you do not want to use any external 3rd party software then you can implement any of these two methods.
Windows Task Scheduler
Windows startup shortcut
Windows Task Scheduler
As mentioned in this answer prepare one start.bat file.
Put this file where nginx.exe is present.
Open windows task scheduler and set up the task as described in this answer to run it indefinitely.
Do not forget to run this task as the highest privilege with the system account, more details can be found here.
Make the task to start daily at a certain time, through the bat file it will check whether the service is already running to avoid creating multiple nginx.exe instances.
If due to some reason Nginx shuts down, within 5 minutes it will start.
Windows Startup shortcut
Create one shortcut of nginx.exe and put it in the startup folder of Windows.
Follow this answer to find your startup location.
Nginx will run automatically whenever you log in to the system.
This one is the easiest. However, it is dependent on user profile i.e. if you are running Nginx on a server, it will run only for your user account, when you log off it stops.
This is ideal for dev environment.
Download zip file from here.
Extract nginx-service.exe from winginx\build and run it.
Rather than turning nginx into a service, or using CMD to start a process, which really doesn't seem to work. I found that Powershell makes it easy to startup nginx as a detached process. I've combined starting nginx with PHP. Below is the script, named "start-nginx.ps1"
$fcgiPort = "127.0.0.1:9000"
$PHPini = "c:\php\php.ini"
$ErrorActionPreference = "SilentlyContinue"
function restart {
Push-Location /nginx
Stop-Process -Force -Name nginx
Start-Process ./nginx.exe -WindowStyle Hidden
Stop-Process -Force -Name php-cgi
Start-Process "c:\php\php-cgi.exe" -ArgumentList ("-b" + $fcgiPort + " -c " + $PHPini) -WindowStyle Hidden
Pop-Location
}
restart
This script can be executed from any directory, but needs to be customized for where your nginx installation is located.
This script includes a silent attempt to kill nginx and PHP before launching both.
Windows systems are supposed to recognize ".ps1" files as powershell, even in the CMD prompt.
I created another small script to kill the running processes, which simply removes the "start-process" lines from this file.
To run at startup, I used the win-R command to navigate to the directory shell:startup
Placing a shortcut to the startup script in this directory, nginx starts at boot!
Powershell also includes a much more sophisticated ability to schedule tasks, and it is possible to schedule this script to run at startup. See This Link
From the article:
>powershell
$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30
Register-ScheduledJob -Trigger $trigger -FilePath $HOME/start-nginx.ps1 -Name startNginx
Combined, I think this approach gets you everything you'd need from an nginx windows service and doesn't require any third-party applications.
Official nginx wiki referes on winginx for this purpose. It builds exe-installer in linux environment.
Process looks like this:
sudo apt-get install nsis make
wget https://github.com/InvGate/winginx/archive/master.zip
unzip master.zip
cd winginx-master/
make
ls -lh ./build/nginx-service.exe
To get actual versions you should specify them in Makefile.

How to uninstall a Windows Service when there is no executable for it left on the system?

How do I uninstall a Windows Service when there is no executable for it left on the system? I can not run installutil -u since there is not executable left on the system. I can still see an entry for the service in the Services console.
The reason for this state is probably because of a problem in the msi package that does not remove the service correctly, but how do I fix it once the service is in this state?
You should be able to uninstall it using sc.exe (I think it is included in the Windows Resource Kit) by running the following in an "administrator" command prompt:
sc.exe delete <service name>
where <service name> is the name of the service itself as you see it in the service management console, not of the exe.
You can find sc.exe in the System folder and it needs Administrative privileges to run. More information in this Microsoft KB article.
Alternatively, you can directly call the DeleteService() api. That way is a little more complex, since you need to get a handle to the service control manager via OpenSCManager() and so on, but on the other hand it gives you more control over what is happening.
Remove Windows Service via Registry
Its very easy to remove a service from registry if you know the right path. Here is how I did that:
Run Regedit or Regedt32
Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"
Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).
Delete Windows Service via Command Window
Alternatively, you can also use command prompt and delete a service using following command:
sc delete
You can also create service by using following command
sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"
Note: You may have to reboot the system to get the list updated in service manager.
Here is the powershell script to delete a service foo
$foo= Get-WmiObject -Class Win32_Service -Filter "Name='foo'"
$foo.delete()
found here
I just tried on windows XP, it worked
local computer:
sc \\. delete [service-name]
Deleting services in Windows Server 2003
We can use sc.exe in the Windows Server 2003 to control services, create services and delete services. Since some people thought they must directly modify the registry to delete a service, I would like to share how to use sc.exe to delete a service without directly modifying the registry so that decreased the possibility for system failures.
To delete a service:
Click “start“ - “run“, and then enter “cmd“ to open Microsoft Command Console.
Enter command:
sc servername delete servicename
For instance, sc \\dc delete myservice
(Note: In this example, dc is my Domain Controller Server name, which is not the local machine, myservice is the name of the service I want to delete on the DC server.)
Below is the official help of all sc functions:
DESCRIPTION:
SC is a command line program used for communicating with the
NT Service Controller and services.
USAGE:
sc
My favourite way of doing this is to use Sysinternals Autoruns application. Just select the service and press delete.
I'd use PowerShell for this
Remove-Service -Name "TestService"
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/remove-service
Create a copy of executables of same service and paste it on the same path of the existing service and then uninstall.

Resources