Solved

Powershell: Try/Catch help

Posted on 2016-11-11
2
27 Views
Last Modified: 2016-11-11
Hello experts,

I have the following code
$mystring = @()
$DCName = "test1.net"
$ServiceName="spooler"
try {   $mystring += Get-Service -ComputerName $DCName  -Name $serviceName | Select name, Status }
 Catch {
$mystring += "$DCName Error"
write-host "Error $DCName"
}

When the DC is down, and I cant connect to this DC, it does not go into the catch block, instead it throws the default error that Get-Service: cannot find any service .....
Please assist.
0
Comment
Question by:Parity123
2 Comments
 
LVL 83

Accepted Solution

by:
oBdA earned 500 total points
ID: 41884198
Turn the cmdlet's non-terminating errors to terminating ones by adding "-ErrorAction Stop" to the arguments:
$mystring = @()
$DCName = "test1.net"
$ServiceName="spooler"
Try {
	$mystring += Get-Service -ComputerName $DCName  -Name $serviceName -ErrorAction Stop | Select name, Status
} Catch {
	$mystring += "$DCName Error"
	write-host "Error $DCName"
}

Open in new window

0
 

Author Closing Comment

by:Parity123
ID: 41884290
Thanks
0

Featured Post

Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

Join & Write a Comment

Microsoft Windows Server Update Service (WSUS) is free for everyone, but it lacks of some desirable features like send an e-mail to the administrator with the status of all computers on the WSUS server. This article is based on my PowerShell script …
Restoring deleted objects in Active Directory has been a standard feature in Active Directory for many years, yet some admins may not know what is available.
This tutorial will walk an individual through the steps necessary to join and promote the first Windows Server 2012 domain controller into an Active Directory environment running on Windows Server 2008. Determine the location of the FSMO roles by lo…
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles to another domain controller. Log onto the new domain controller with a user account t…

758 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

20 Experts available now in Live!

Get 1:1 Help Now