Solved

Modifying Powershell script to change service startup mode ?

Posted on 2016-11-28
9
17 Views
Last Modified: 2016-11-30
Hi All,

I've got this powershell code by one of the expert in this forum to display all services with the name like "App1" for the servers in certain OU location running perfectly fine exporting to .CSV:

$path = "C:\TEMP"
$ServiceName = "App1"
$SearchBase = "OU=Application Servers,OU=Servers,DC=domain,DC=com"
$Properties = 'Name', 'DisplayName', 'State', 'StartMode', 'StartName'

$ServerList = Get-ADComputer -Properties Name -Filter {Enabled -eq $True -and OperatingSystem -like "*Windows Server*"} -SearchBase $SearchBase |
	Where-Object {$_.DistinguishedName -notlike "*OU=Decommissioned Servers,DC=domain,DC=com"}

$ServiceList = ForEach ($Server in $ServerList) {
	$(Try {
		Write-Host "Processing $($Server.Name) ..." -ForegroundColor White -NoNewline
		If (-not (Test-Connection -ComputerName $Server.DNSHostName -Count 1 -Quiet)) {
			Throw "Offline"
		}
		Get-WmiObject -Query "SELECT $($Properties -join ',') FROM Win32_Service WHERE DisplayName LIKE '%$($ServiceName)%'" -ErrorAction Stop -ComputerName $Server.DNSHostName
		$Exception = $Null
		Write-Host " OK." -ForegroundColor Green
	} Catch {
		$Exception = $_.Exception.Message
		''
		Write-Host " $($Exception)" -ForegroundColor Red
	}) | Select-Object -Property (@(@{n='ComputerName'; e={$Server.Name}}) + $Properties + @{n='Exception'; e={$Exception}})
}

$ServiceList | Export-Csv -Path $path\ResultSVC-App1.csv -NoClobber -NoTypeInformation -UseCulture

Open in new window


Now, how do I edit the script above so that the startup type is Automatic and Service Status is Running without causing the service to be rebooted or restarted if it is already running.

Using this line:
Set-Service -Name App1 -StartupType Automatic

Open in new window


Any help would be greatly appreciated.

Thanks
0
Comment
  • 4
  • 4
9 Comments
 
LVL 82

Expert Comment

by:oBdA
Comment Utility
$path = "C:\TEMP"
$ServiceName = "App1"
$SearchBase = "OU=Application Servers,OU=Servers,DC=domain,DC=com"

$Properties = 'ComputerName', 'Name', 'DisplayName', 'State', 'StartMode', 'StartName', 'Start_Changed', 'Started', 'Exception'

$ServerList = Get-ADComputer -Properties Name -Filter {Enabled -eq $True -and OperatingSystem -like "*Windows Server*"} -SearchBase $SearchBase |
	Where-Object {$_.DistinguishedName -notlike "*OU=Decommissioned Servers,DC=domain,DC=com"}

$ServiceList = ForEach ($Server in $ServerList) {
	$Return = '' | Select-Object -Property $Properties
	$Return.ComputerName = $Server.Name
	Try {
		Write-Host "Processing $($Server.Name) ..." -ForegroundColor White -NoNewline
		If (-not (Test-Connection -ComputerName $Server.DNSHostName -Count 1 -Quiet)) {
			Throw "Offline"
		}
		$Service = Get-WmiObject -Query "SELECT * FROM Win32_Service WHERE DisplayName LIKE '%$($ServiceName)%'" -ErrorAction Stop -ComputerName $Server.DNSHostName
		'Name', 'DisplayName', 'State', 'StartMode', 'StartName' | ForEach-Object {
			$Return.$_ = $Service.$_
		}
		If ($Service.StartMode -ne 'Auto') {
			Write-Host " setting AutoStart ..." -ForegroundColor Yellow -NoNewline
			Set-Service -Name $Service.Name -StartupType Automatic -ErrorAction Stop
			$Return.Start_Changed = $True
		} Else {
			Write-Host " AutoStart OK ..." -ForegroundColor Green -NoNewline
			$Return.Start_Changed = $False
		}
		If ($Service.State -eq 'Stopped') {
			Write-Host " starting ..." -ForegroundColor Yellow -NoNewline
			Start-Service -Name $Service.Name -ErrorAction Stop
			$Return.Started = $True
		} Else {
			Write-Host " running ..." -ForegroundColor Green -NoNewline
			$Return.Started = $False
		}
		Write-Host " OK." -ForegroundColor Green
	} Catch {
		$Return.Exception = $_.Exception.Message
		Write-Host " $($Return.Exception)" -ForegroundColor Red
	} Finally {
		$Return
	}
}

$ServiceList | Export-Csv -Path $path\ResultSVC-App1.csv -NoClobber -NoTypeInformation -UseCulture

Open in new window

1
 
LVL 7

Author Comment

by:Senior IT System Engineer
Comment Utility
Thanks for the quick reply OBDA,
So in this case if I add -WhatIf on the line that change the service mode, I can see which services going to be impacted on the CSV result file ?
0
 
LVL 7

Author Comment

by:Senior IT System Engineer
Comment Utility
Is there any service outage when executing the script to change the service mode ?
0
 
LVL 82

Expert Comment

by:oBdA
Comment Utility
Hold on, scratch that, doesn't work properly remotely, sorry; was about to delete when you posted. Let me fix that ...
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 82

Expert Comment

by:oBdA
Comment Utility
You can now call the script with -WhatIf to see if it would change anything.
There should be no service outage even if the startup mode is changed.
Param([switch]$WhatIf)
$path = "C:\TEMP"
$ServiceName = "App1"
$SearchBase = "OU=Application Servers,OU=Servers,DC=domain,DC=com"

$Properties = 'ComputerName', 'Name', 'DisplayName', 'State', 'StartMode', 'StartName', 'Start_Changed', 'Started', 'Exception'

$ServerList = Get-ADComputer -Properties Name -Filter {Enabled -eq $True -and OperatingSystem -like "*Windows Server*"} -SearchBase $SearchBase |
	Where-Object {$_.DistinguishedName -notlike "*OU=Decommissioned Servers,DC=domain,DC=com"}

$ServiceList = ForEach ($Server in $ServerList) {
	Try {
		Write-Host "Processing $($Server.Name) ..." -ForegroundColor White -NoNewline
		If (-not (Test-Connection -ComputerName $Server.DNSHostName -Count 1 -Quiet)) {
			Throw "Offline"
		}
		ForEach ($Service In (Get-WmiObject -Query "SELECT * FROM Win32_Service WHERE DisplayName LIKE '%$($ServiceName)%'" -ErrorAction Stop -ComputerName $Server.DNSHostName)) {
			$Return = '' | Select-Object -Property $Properties
			$Return.ComputerName = $Server.Name
			'Name', 'DisplayName', 'State', 'StartMode', 'StartName' | ForEach-Object {
				$Return.$_ = $Service.$_
			}
			If ($Service.StartMode -ne 'Auto') {
				Write-Host " setting AutoStart$(If ($WhatIf) {' (WhatIf)'}) ..." -ForegroundColor Yellow -NoNewline
				If ($WhatIf) {
					$Return.Exception = 'WhatIf'
				} Else {
					$Result = $Service.ChangeStartMode('Automatic')
					If ($Result.ReturnValue -ne 0) {
						Throw "Error $($Result.ReturnValue) trying to change the startup type to automatic."
					}
				}
				$Return.Start_Changed = $True
			} Else {
				Write-Host " AutoStart OK ..." -ForegroundColor Green -NoNewline
				$Return.Start_Changed = $False
			}
			If ($Service.State -eq 'Stopped') {
				Write-Host " starting$(If ($WhatIf) {' (WhatIf)'}) ..." -ForegroundColor Yellow -NoNewline
				If ($WhatIf) {
					$Return.Exception = 'WhatIf'
				} Else {
					$Result = $Service.StartService()
					If ($Result.ReturnValue -ne 0) {
						Throw "Error $($Result.ReturnValue) trying to start the service."
					}
				}
				$Return.Started = $True
			} Else {
				Write-Host " running ..." -ForegroundColor Green -NoNewline
				$Return.Started = $False
			}
			Write-Host " OK." -ForegroundColor Green
			$Return
		}
	} Catch {
		$Return = '' | Select-Object -Property $Properties
		$Return.ComputerName = $Server.Name
		$Return.Exception = $_.Exception.Message
		Write-Host " $($Return.Exception)" -ForegroundColor Red
		$Return
	}
}

$ServiceList | Export-Csv -Path $path\ResultSVC-App1.csv -NoClobber -NoTypeInformation -UseCulture

Open in new window

1
 
LVL 78

Assisted Solution

by:David Johnson, CD, MVP
David Johnson, CD, MVP earned 50 total points
Comment Utility
do you want to set the service start type to 'automatic' if it is NOT automatic?
Set-Service can change the start type
get-help set-service -examples
1
 
LVL 7

Author Comment

by:Senior IT System Engineer
Comment Utility
Thanks All for the reply.

So I have saved the script into Script1.ps1, but when I run it using:

C:\Powershell scripts> '.\Script1.ps1' -WhatIf
At line:1 char:69
+ ... -Script1.ps1' -WhatIf
+                                                                   ~~~~~~~
Unexpected token '-WhatIf' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

Open in new window


Also is this because I change the source of item / lines using:

$ServerList = Get-Content -Path C:\temp\App1.txt

Open in new window


using Text file with the format like:

Server1
Server2
...
ServerN
0
 
LVL 82

Accepted Solution

by:
oBdA earned 450 total points
Comment Utility
In Powershell, when you enclose a file name to execute in quotes, you need to add an ampersand in front to tell PS that there's a command to execute following, otherwise it'll be treated as a string:
& '.\Script1.ps1' -WhatIf

Open in new window

In the script above, you can't just switch the source, as the loop is relying on AD objects with properties. This one can use both, provided the server list has one server name per line.
Param([switch]$WhatIf)
$path = "C:\TEMP"
$ServiceName = "App1"
$SearchBase = "OU=Application Servers,OU=Servers,DC=domain,DC=com"

$Properties = 'ComputerName', 'Name', 'DisplayName', 'State', 'StartMode', 'StartName', 'Start_Changed', 'Started', 'Exception'

# $ServerList = Get-ADComputer -Properties Name -Filter {Enabled -eq $True -and OperatingSystem -like "*Windows Server*"} -SearchBase $SearchBase |
	# Where-Object {$_.DistinguishedName -notlike "*OU=Decommissioned Servers,DC=domain,DC=com"} |
	# Select-Object -ExpandProperty Name

$ServerList = Get-Content -Path C:\temp\App1.txt
	
$ServiceList = ForEach ($ServerName in $ServerList) {
	Try {
		Write-Host "Processing $($ServerName) ..." -ForegroundColor White -NoNewline
		If (-not (Test-Connection -ComputerName $ServerName -Count 1 -Quiet)) {
			Throw "Offline"
		}
		ForEach ($Service In (Get-WmiObject -Query "SELECT * FROM Win32_Service WHERE DisplayName LIKE '%$($ServiceName)%'" -ErrorAction Stop -ComputerName $ServerName)) {
			$Return = '' | Select-Object -Property $Properties
			$Return.ComputerName = $ServerName
			'Name', 'DisplayName', 'State', 'StartMode', 'StartName' | ForEach-Object {
				$Return.$_ = $Service.$_
			}
			If ($Service.StartMode -ne 'Auto') {
				Write-Host " setting AutoStart$(If ($WhatIf) {' (WhatIf)'}) ..." -ForegroundColor Yellow -NoNewline
				If ($WhatIf) {
					$Return.Exception = 'WhatIf'
				} Else {
					$Result = $Service.ChangeStartMode('Automatic')
					If ($Result.ReturnValue -ne 0) {
						Throw "Error $($Result.ReturnValue) trying to change the startup type to automatic."
					}
				}
				$Return.Start_Changed = $True
			} Else {
				Write-Host " AutoStart OK ..." -ForegroundColor Green -NoNewline
				$Return.Start_Changed = $False
			}
			If ($Service.State -eq 'Stopped') {
				Write-Host " starting$(If ($WhatIf) {' (WhatIf)'}) ..." -ForegroundColor Yellow -NoNewline
				If ($WhatIf) {
					$Return.Exception = 'WhatIf'
				} Else {
					$Result = $Service.StartService()
					If ($Result.ReturnValue -ne 0) {
						Throw "Error $($Result.ReturnValue) trying to start the service."
					}
				}
				$Return.Started = $True
			} Else {
				Write-Host " running ..." -ForegroundColor Green -NoNewline
				$Return.Started = $False
			}
			Write-Host " OK." -ForegroundColor Green
			$Return
		}
	} Catch {
		$Return = '' | Select-Object -Property $Properties
		$Return.ComputerName = $ServerName
		$Return.Exception = $_.Exception.Message
		Write-Host " $($Return.Exception)" -ForegroundColor Red
		$Return
	}
}

$ServiceList | Export-Csv -Path $path\ResultSVC-App1.csv -NoClobber -NoTypeInformation -UseCulture

Open in new window

1
 
LVL 7

Author Closing Comment

by:Senior IT System Engineer
Comment Utility
Thanks it works.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now