Solved

Modifying Powershell script to change service startup mode ?

Posted on 2016-11-28
9
44 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 83

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 7

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 7

Author Comment

by:Senior IT System Engineer
ID: 41905236
Is there any service outage when executing the script to change the service mode ?
0
 
LVL 83

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
[Webinar] Disaster Recovery and Cloud Management

Learn from Unigma and CloudBerry industry veterans which providers are best for certain use cases and how to lower cloud costs, how to grow your Managed Services practice in IaaS clouds, and how to utilize public cloud for Disaster Recovery

 
LVL 83

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 78

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 7

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 83

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 7

Author Closing Comment

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

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

The article will show you how you can maintain a simple logfile of all Startup and Shutdown events on Windows servers and desktops with PowerShell. The script can be easily adapted into doing more like gracefully silencing/updating your monitoring s…
Set OWA language and time zone in Exchange for individuals, all users or per database.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

911 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

19 Experts available now in Live!

Get 1:1 Help Now