Solved

powershell try catch statement

Posted on 2013-02-01
2
750 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
Comment Utility
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
Comment Utility
Thanks for the clarification.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

How to sign a powershell script so you can prevent tampering, and only allow users to run authorised Powershell scripts
I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

762 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now