Solved

Powershell: Try/Catch help

Posted on 2016-11-11
2
104 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

The Nano Server Image Builder helps you create a custom Nano Server image and bootable USB media with the aid of a graphical interface. Based on the inputs you provide, it generates images for deployment and creates reusable PowerShell scripts that …
This article shows the method of using the Resultant Set of Policy Tool to locate Group Policy that applies a particular setting.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.

734 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