Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Powershell: Try/Catch help

Posted on 2016-11-11
2
Medium Priority
?
159 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 85

Accepted Solution

by:
oBdA earned 2000 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

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

Question has a verified solution.

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

A walk-through example of how to obtain and apply new DID phone numbers to your cloud PBX enabled users that are configured in Office 365. Whether you have 1, 10 or 100+ users in your tenant, it's quite easy to get them phone-enabled and making/rece…
Phishing emails are a popular malware delivery vehicle for attack.  While there are many ways for an attacker to increase the chances of success for their phishing emails, one of the most effective methods involves spoofing the message to appear to …
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…

916 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