?
Solved

Modifying Powershell script to change service startup mode ?

Posted on 2016-11-28
9
Medium Priority
?
85 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
Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

 
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 82

Assisted Solution

by:David Johnson, CD, MVP
David Johnson, CD, MVP earned 200 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 1800 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

The Nano Server Image Builder helps you create a custom Nano Server image and bootable USB media with the aid of a graphical interface. Based on the inputs you provide, it generates images for deployment and creates reusable PowerShell scripts that …
There are times when we need to generate a report on the inbox rules, where users have set up forwarding externally in their mailbox. In this article, I will be sharing a script I wrote to generate the report in CSV format.
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…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

777 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