How To Modify a Windows Service

Here’s the freebie code:

# Version 0.02

$serviceName='Windows_Exporter'
$newExePath=$false
$newSwitches=" --log.format logger:eventlog?name=$serviceName --collectors.enabled os,cpu,cs,logical_disk,net,tcp,service,textfile"

function modifyService{
    param(
        $serviceName='windows_exporter',
        $newExePath=$false,
        $newSwitches=$false
    )
    $wmiService=Get-WmiObject win32_service| ?{$_.Name -like "*$serviceName*"}
    $pathToExecute=$wmiService.PathName
    $originalExePath=[regex]::match($pathToExecute,'\"(.*)\"').groups[1].value
    write-host "Original Path To Execute: $pathToExecute"
    $charIndexOfSwitches=try{$pathToExecute.indexof(' -')}catch{}
    $originalSwitches=if($charIndexOfSwitches -ne -1){
        $pathToExecute.Substring($pathToExecute.indexof(' -'))
        }else{$null}
    $switches=if($newSwitches){$newSwitches}else{$originalSwitches}
    $exePath=if((test-path $newExePath) -and $newExePath -ne $originalExePath){$newExePath}else{$originalExePath}
    $binarySwitches='\"' + $exePath + '\"' + $switches
    write-host "New path to execute: $binarySwitches"
    $output=sc.exe config $serviceName binpath= $binarySwitches
    write-host $output
    $output=sc.exe qc $serviceName
    $output|write-host
    restart-service $serviceName
}

modifyService $serviceName $newExePath $newSwitches

This is an example of how to modify a service named Windows_Exporter:

# Enabling Collectors for a Hyper-V Server
$serviceName='Windows_Exporter'
$enabledCollectors='os,cpu,cs,logical_disk,net,tcp,hyperv,service,textfile'
$switches=" --log.format logger:eventlog?name=$serviceName --collectors.enabled $enabledCollectors"
$resets=30
$restartWaitMs=100000
$maxWaitSeconds=120

function modifyService{
	param(
		$serviceName,
		$switches,
		$resets=30,
		$restartWaitMs=100000,
		$maxWaitSeconds=120
	)	
	$wmiService=Get-WmiObject win32_service| ?{$_.Name -like "*$serviceName*"}
	$exePath=[regex]::match($wmiService.PathName,'\"(.*)\"').groups[1]
	$binarySwitches='\"' + $exePath + '\"' + $switches
	sc.exe config $serviceName binpath= $binarySwitches
	# Set auto start and restart upon failures
	$null=& sc.exe failure $serviceName reset= $resets actions= restart/$restartWaitMs/restart/$restartWaitMs/""/$($restartWaitMs*3)
	Set-Service -Name $serviceName -StartupType 'Automatic'
	sc.exe qc windows_exporter
	restart-service $serviceName
}

# Local execution
modifyService $serviceName $switches
# Remote execution
$computerNames=@(
	'HyperV001',
	'HyperV002',
	'HyperV003',
	'HyperV004'
)
foreach($computer in $computernames){
	write-host "Executing function on $computer..."
	invoke-command -computername $computer -scriptblock {
			param($modifyService,$servicename,$switches)
			[ScriptBlock]::Create($modifyService).Invoke($servicename,$switches)
		} -Args ${function:modifyService},$servicename,$switches
}

Leave a Reply

Your email address will not be published. Required fields are marked *