Solved

Modifying Powershell script to change service startup mode ?

Posted on 2016-11-28
9
76 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
9 Comments
 
LVL 85

Expert Comment

by:oBdA
ID: 41905232
$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 8

Author Comment

by:Senior IT System Engineer
ID: 41905235
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 8

Author Comment

by:Senior IT System Engineer
ID: 41905236
Is there any service outage when executing the script to change the service mode ?
0
Free eBook: Backup on AWS

Everything you need to know about backup and disaster recovery with AWS, for FREE!

 
LVL 85

Expert Comment

by:oBdA
ID: 41905237
Hold on, scratch that, doesn't work properly remotely, sorry; was about to delete when you posted. Let me fix that ...
0
 
LVL 85

Expert Comment

by:oBdA
ID: 41905262
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 81

Assisted Solution

by:David Johnson, CD, MVP
David Johnson, CD, MVP earned 50 total points
ID: 41905278
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 8

Author Comment

by:Senior IT System Engineer
ID: 41906797
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 85

Accepted Solution

by:
oBdA earned 450 total points
ID: 41906807
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 8

Author Closing Comment

by:Senior IT System Engineer
ID: 41908188
Thanks it works.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This script can help you clean up your user profile database by comparing profiles to Active Directory users in a particular OU, and removing the profiles that don't match.
A recent project that involved parsing Tableau Desktop and Server log files to extract reusable user queries for use in other systems. I chose to use PowerShell to gather the data, and SharePoint to present it...
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…

726 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