Solved

powershell try catch statement

Posted on 2013-02-01
2
760 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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

Create and license users in Office 365 in bulk based on a CSV file. A step-by-step guide with PowerShell script examples.
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

808 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