Solved

powershell try catch statement

Posted on 2013-02-01
2
758 Views
Last Modified: 2013-02-05
Im trying to see if I can use Try Catsch to move AD accounts. Sometines you will have accounts that already exist in the destination container. I can use Try Catch and I can see the accounts that cannot be moved. However, I cant seem to collect them so that I can re-process them in a different way
$aduser | % {

try {
   move-qadobject $_.dn -newparentcontainer $ou | out-null
}
catch {
   $problemusers += $_.dn
}

$problemusers is blank


try {
   move
0
Comment
Question by:bndit
2 Comments
 
LVL 70

Accepted Solution

by:
Chris Dent earned 285 total points
ID: 38846618
Hmm don't use Try / Catch, they do the wrong thing for this really. That is, they trap unhandled exceptions and aren't the best way to catch output from CmdLets throwing terminating errors.

Perhaps try:
Move-QADObject $_.DN -NewParentContainer $ou -ErrorAction SilentlyContinue | Out-Null
# Test whethe the last command succeeded with the reserved variable $?.
# Negated with !, testing for $? set to False
If (!$?) {
  $problemusers += $_.dn
}

Open in new window

You could also check for something before moving, worth noting even if it's an approach you wish to use :)
If (!(Get-QADObject $_.Name -SearchRoot $OU)) {
  Move-QADObject $_.DN -NewParentContainer $OU | Out-Null
}

Open in new window

HTH

Chris
0
 
LVL 2

Author Closing Comment

by:bndit
ID: 38858158
Thanks for the clarification.
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

This article will help you understand what HashTables are and how to use them in PowerShell.
This script can help you clean up your user profile database by comparing profiles to Active Directory users in a particular OU, and removing the profiles that don't match.
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

773 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