Skip to content

Instantly share code, notes, and snippets.

@ScriptAutomate
Created April 29, 2015 11:53
Show Gist options
  • Save ScriptAutomate/fc4f9f4aab48a5738def to your computer and use it in GitHub Desktop.
Save ScriptAutomate/fc4f9f4aab48a5738def to your computer and use it in GitHub Desktop.
Set-ServiceStartupMode [For PowerShell v2+]
# For PowerShell v2; Otherwise, Set-Service cmdlet exists in v3+ with -StartupType parameter!
function Set-ServiceStartupMode {
[CmdletBinding()]
param (
[String[]]$ComputerName,
[String]$ServiceName,
[ValidateSet("Boot","System","Automatic","Manual","Disabled")]
[String]$StartupMode,
[Parameter(Mandatory=$False)]
[Management.Automation.PSCredential]$Credential
)
Invoke-Command -ComputerName $ComputerName -Credential $Credential -ScriptBlock {
$Service = Get-WmiObject win32_service -Filter "Name=`'$($args[0])`'" #Retrieve
if ($Service) {
$NULL = $Service.ChangeStartMode("$($args[1])") #Change
$Service | select Name,Status,StartMode #Verify
}
else {
Write-Error "$($args[0]) not found."
}
} -ArgumentList $ServiceName,$StartupMode
}
# Example use of function
$ServerLists = @("srv100","srv101","srv102","srv103")
Set-ServiceStartupMode -ComputerName $ServerLists `
-ServiceName winrm `
-StartupMode Automatic `
-Credential (Get-Credential) # For alternate credentials
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment