?
Solved

Modifying Powershell script to change service startup mode ?

Posted on 2016-11-28
9
Medium Priority
?
93 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 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
Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

 
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 84

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

Veeam and MySQL: How to Perform Backup & Recovery

MySQL and the MariaDB variant are among the most used databases in Linux environments, and many critical applications support their data on them. Watch this recorded webinar to find out how Veeam Backup & Replication allows you to get consistent backups of MySQL databases.

Question has a verified solution.

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

When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
Measuring Server's processing rate with a simple powershell command. The differences in processing rate also was recorded in different use-cases, when a server in free and busy states.
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…
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 anti-spam), the admin…

862 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