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?
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.)
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.)
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.