PowerShell File monitor at Windows startup - events

I have a file system monitoring PowerShell script using System.IO.FileSystemWatcher events.
The script works great, but it requires an open PowerShell window.
Thus, I need to run it as a Windows Service at Windows startup (without logon). Is there a way to do this?

To execute your script at windows startup (without logon) you could create a windows service for it (using srvany.exe).
Steps:
Get the windows 2003 resource kit (which contains srvany.exe)
Install the resource kit
Create the service using sc and srvany.exe
sc create PSService binPath= "C:\Program Files\Windows Resource Kits\Tools\srvany.exe" DisplayName= "PSService"
Parametrize your service
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\PSService]
"Type"=dword:00000010
"Start"=dword:00000003
"ErrorControl"=dword:00000001
"DisplayName"="PSService"
"ObjectName"="LocalSystem"
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\PSService\Parameters]
"Application"="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -noExit -ExecutionPolicy RemoteSigned -File C:\\PSService\\psservice.ps1"
Some remarks:
Srvany.exe is not available for Windows Vista and up. It might work, but it's probably not supported
You might want to run it with other credentials (for security reasons)
You might want to save your script in a directory where only administrators have write access (for security reasons)

Related

How to create windows service to run a powershell script?

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

How to run batch file (As administrator) from Window Service

I have created a windows service, its running fine.
Now I would like to run a batch file as Administrator using windows service, because without administrator privileges it doesn't return any output.
So please let me know how can I do that. When I run directly using right click, run as administrator its working fine. Batch file as follows:
Runas.exe /noprofile /user:"Laxmilal Menaria" "lm.exe"
Thanks,
Laxmilal Menaria

Permissions Elevation for Windows 7?

Ive got a java app which needs to execute a driver installer exe file. On Linux we type "gksudo myCommand". Is there a way to elevate permissions from Windows command line?
You may run every application in windows with a different user e.g. Administrator. But the user who executes this command needs to have the credentials to do so.
Edit.:
In advance you can lookup the User Account Control (UAC) which is available in Windows 7 and Vista if it is possibly an alternative for you.
I decided to deploy an executable binary onto the system which calls the jar. This way the user can right click and run as administrator... That didn't work... SO I kept looking... Check this out..
Elevate.exe.. It's basically like Windows GKSudo!!!!
http://www.robotronic.de/elevate.html
So... I packaged the 32bit exe into my program and deploy it, then run it as necessary.
You can use runas command like runas /user:Administrator myCommand (it requires the users to type password).
You can also use Start-Process cmdlet like Start-Process -Verb runas myCommand in PowerShell (it requires the users to click the UAC dialog).
see: http://satob.hatenablog.com/entry/2017/06/17/013217

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.

Running Batch File in background when windows boots up

How do I run a batch file each time windows boots up also I need to run it in the back ground(without that command window getting displayed)? I use Windows Xp.
My actuall requirement is I want to start the Tracd server using the command line commands whenever Windows boots up.
Add your program in the registry:
Run - These are the most common startup locations for programs to install auto start from. By default these keys are not executed in Safe mode. If you prefix the value of these keys with an asterisk, *, is will run in Safe Mode.
Registry Keys:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run registry key
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run registry key
Then you can launch your batch in an invisible mode:
wscript.exe "C:\yourpath\invis.vbs" "your_file.bat"
In invis.vbs put...
CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False
Two other startup posibilties:
you could always add the bat file to the startup folder,
or start it as a Scheduled task setting to run on logon.
You can make an application run as a service.
Check this article for details:
You can use autoexnt for this. It was original designed for windows NT, but is still working in newer versions of windows.
You have to download the Windows 2003 Resource Kit to get it.
There's also hstart, a third party program that's worked well for my needs. It's maintained too. The last version was released on July 7, 2010.

Resources