New Service - PowerShell
Overview
The New-Service
command in PowerShell allows you to create and configure new services on a Windows system. It simplifies the process of defining service properties, dependencies, and actions for various tasks, including starting, stopping, and monitoring the service.
Syntax
New-Service [[-Name] <string>] [-DisplayName <string>] [-Description <string>] [-StartupType <string>] [-Path <string>] [-Arguments <string>] [-Credential <PSCredential>] [-ServiceDependencies <string[]>] [-ServiceConfig [<ServiceConfigFlags>]] [-ManagedAccount <string>] [-RecoveryCommand <string>] [-RestartCount <int>] [-RestartInterval <TimeSpan>]
Options/Flags
- -Name: The name of the new service to be created.
- -DisplayName: The display name of the service, which will appear in services management tools.
- -Description: A description of the service’s purpose.
- -StartupType: The startup type of the service, controlling when it starts automatically (Automatic, Manual, Disabled).
- -Path: The path to the executable or script that runs the service.
- -Arguments: The arguments passed to the service when it starts.
- -Credential: The credentials of the account under which the service will run.
- -ServiceDependencies: Dependencies on other services that must be running before this service can start.
- -ServiceConfig: Custom configuration flags for the service, such as DNS, REPLICATOR, TRIGGERED.
- -ManagedAccount: Specifies a managed service account for the service to run under.
- -RecoveryCommand: A command that is executed if the service fails.
- -RestartCount: The number of times the service should be restarted if it fails.
- -RestartInterval: The time interval between service restart attempts.
Examples
To create a simple service:
New-Service -Name "MyService" -DisplayName "My Service" -Path "C:\path\to\myservice.exe"
To create a service with dependencies and recovery actions:
New-Service -Name "MyService" -DisplayName "My Service" -Path "C:\path\to\myservice.exe" -ServiceDependencies "MSSQLSERVER" -RecoveryCommand "C:\path\to\recoveryscript.ps1" -RestartCount 3 -RestartInterval "00:10:00"
Common Issues
- Verifying that the specified path points to a valid executable or script.
- Ensure that the service account has sufficient permissions to run the service.
- Troubleshooting startup errors by checking the service’s event log.
Integration
The New-Service
command can be combined with other PowerShell commands for advanced automation tasks. For example:
Install-WindowsFeature -Name "IIS-WebServerRole" | New-Service -Name "W3SVC" -DisplayName "World Wide Web Publishing Service"
Related Commands
- Get-Service: Retrieves information about existing services.
- Set-Service: Modifies the properties of an existing service.
- Restart-Service: Restarts an existing service.
- Stop-Service: Stops an existing service.