Help with exception.

I’m creating a script to update active directory. How would I go about putting a exception on the code if the attribute “department” has no data or is blank in the csv file?

Import-CSV $importfile | ForEach-Object{
$samaccountname = $.sAMAccountName.ToLower()
$department = $
.department
$phone = $.Phone
$emailAddress = $
.emailAddress
$manager = $_.manager.ToLower()

Try {
$exists = Get-ADUser -LDAPFilter “(sAMAccountName=$samaccountname)”
}
Catch
{
write-host “Users did not exist.”
}
If ($exists)
{

    If ($department) 
    { 
        Set-ADUser -Identity $samaccountname -department $department
    }

To produce your own errors in a script, you can either use Write-Error (for nonterminating errors) or throw (for terminating errors); which one you use depends on whether you want the whole pipeline to abort or not. In this case, the answer is probably “not”, so you can continue to process other users, so you’d do something like this:

Import-CSV $importfile | ForEach-Object{
    $samaccountname = $_.sAMAccountName.ToLower()
    $department = $_.department
    $phone = $_.Phone
    $emailAddress = $_.emailAddress
    $manager = $_.manager.ToLower()

    if (-not $department)
    {
        Write-Error "User $samaccountname has no department value in the CSV file."
        return
    }

    # etc.
}

Using the return keyword may look a little bit odd here, but that’s how you move into the next input object in a ForEach-Object loop. (This is just like the Process block of a function, in that regard.)

Dave, why did you use ‘return’ there? I’d typically use ‘continue’. Is using ‘return’ better?

You would use ‘continue’ if you’re in a foreach ($thing in $things) loop, but when you’re in a pipeline with ForEach-Object, using ‘continue’ or ‘break’ makes funny things happen. (Usually, it aborts your whole script, unless there happens to be a loop or switch statement in play farther up the call stack which can process those keywords.)

Ah, guess I’m used to using the foreach statement rather than ForEach-Object.

Yep, if you’ve already got a collection in memory, that’s the way to go. The pipeline has its advantages, though; namely streaming objects so you can process very large data sets without running into OutOfMemory exceptions.

That seemingly is the ONLY advantage. In my experience, it’s always slower than other methods.

True. :slight_smile: Though you can accomplish some pretty impressive speeds using filters, depending on what you’re doing, and still keep memory usage down.