Solved

Powershell: Try/Catch help

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

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

While rebooting windows server 2003 server , it's showing "active directory rebuilding indices please wait" at startup. It took a little while for this process to complete and once we logged on not all the services were started so another reboot is …
This article runs through the process of deploying a single EXE application selectively to a group of user.
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…
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …

791 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