Solved

Powershell: Try/Catch help

Posted on 2016-11-11
2
75 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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

This article runs through the process of deploying a single EXE application selectively to a group of user.
The following article is intended as a guide to using PowerShell as a more versatile and reliable form of application detection in SCCM.
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 from a Windows Server 2008 domain controller to a Windows Server 2012 domain controlle…

786 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