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
		}
	}
}
Advertisements