Start, Stop & Re-Start Windows Service from PowerShell

Start

start-service FIMService

 

Stop

stop-service FIMService

 

Restart

restart-service FIMService

FIMService is the Forefront Identity Manager Service. You can replace this name with the name of the service upon which you’d like to perform any of the above action.

Here’s a zip file which contains the following ps1 script and a csv file.The script will loop through the associated csv file and as per the config, will start, stop and re-start the given service(s). It will also create a Logs folder in the directory from where the script will be executed. All the logs pertaining to the current operation will be stored in this Logs directory.

 



Function LogMessage($strMsg, $lgFlNm)
{
	$strMsg | out-file -Filepath $lgFlNm -append
}

$filePath = [System.IO.Path]::Combine($PSScriptRoot, “config.csv”)
$logFilePath = [System.IO.Path]::Combine($PSScriptRoot, “Logs”)

$logFileName = [System.IO.Path]::Combine($logFilePath, ("ServiceLog_" + [string](get-date -format "yyyyMMdd_hhmmtt") + ".txt"))
$configFile = Import-Csv $filePath

foreach ($servc in $configFile){
	$servc | ForEach-Object {

		try{
			if([String]::IsNullOrWhiteSpace($_.Start) -ne $true){
				LogMessage (“************************************************************”) $logFileName
				LogMessage (“Start:: “ + $_.Start) $logFileName
				LogMessage (start-service $_.Start -passthru *>&1) $logFileName
			}
		}
		catch{
			LogMessage (“Error:: “ + $_.Exception.Message) $logFileName
		}

		try{
			if([String]::IsNullOrWhiteSpace($_.Stop) -ne $true){
				LogMessage (“************************************************************”) $logFileName
				LogMessage (“Stop:: “ + $_.Stop) $logFileName
				LogMessage (stop-service $_.Stop -force -passthru *>&1) $logFileName
			}
		}
		catch{
			LogMessage (“Error:: “ + $_.Exception.Message) $logFileName
		}

		try{
			if([String]::IsNullOrWhiteSpace($_.Restart) -ne $true){
				LogMessage (“************************************************************”) $logFileName
				LogMessage (“Restart:: “ + $_.Restart) $logFileName
				LogMessage (restart-service $_.Restart -PassThru *>&1) $logFileName
			}
		}
		catch{
			LogMessage (“Error:: “ + $_.Exception.Message) $logFileName
		}
	}
}

Log Messages from a Command in PowerShell

Objective

When we run a cmdlet directly in PowerShell, any error, warning, or info regarding the same gets displayed in the console.

Here, I also want to capture the same messages but while running a ps1 script so as to log them down in a separate file. Since, I’ll schedule the script to always run on machine startup, cmdlets like, Start-Transcript & Stop-Transcript won’t be of any help as I’ll have to run the script in -NonInteractive mode of PowerShell.

Why -passthru

Before getting into the solution part, I’d first like to talk about the Powershell parameter, -passthru. -passthru is for the cmdlets that do not return any data. Here, in the current example, I am using the the cmdlet, start-service to start a windows service. By default, it does not return anything and silently continues except, for errors. If I add -passthru parameter to this cmdlet then, a service object is returned containing all the details of the service upon which the cmdlet is executed. Now I can use this object to track the status of the service and consequently log them down.

Solution

So -passthru will return the object which in turn I can use for logging. However, I still need to redirect this output to a file. To do that, I’ll run the following cmdlet

start-service SPTimerV4 -passthru *>&1

This will return the stream which can be easily redirected to a file. Mission accomplished!

Explanation

*>&1 is a Windows PowerShell redirection operator which sends all output types (*) to the success output stream, So weather the command resulted in an error or it ran successfully, every thing is now getting captured and subsequently logged down.

There are other redirection operators as well. They are defined in the following technet article,
https://technet.microsoft.com/en-us/library/hh847746.aspx