Mikhail Kislitsyn
Mikhail Kislitsyn

Reputation: 176

PowerShell File monitor at Windows startup

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?

Upvotes: 1

Views: 1661

Answers (1)

jon Z
jon Z

Reputation: 16626

To execute your script at windows startup (without logon) you could create a windows service for it (using srvany.exe). Steps:

  1. Get the windows 2003 resource kit (which contains srvany.exe)
  2. Install the resource kit
  3. Create the service using sc and srvany.exe

    sc create PSService binPath= "C:\Program Files\Windows Resource Kits\Tools\srvany.exe" DisplayName= "PSService"
    
  4. 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)

Upvotes: 2

Related Questions