0
votes

I've got a Powershell script written at work mass-disabling users based on the given username in a CSV.

This week I was asked to do a bulk job but was only given e-mail addresses so I amended the script & CSV.

What I'd like to do now is to keep the CSV with headers "Username" & "Email" and then have the script find the Distinguished Name based on whichever value is given.

Eg.:

enter image description here

Here is the script I've currently got that has got both values in the script (script modified slightly to remove sensitive data). The script has to search on two different servers as we have users across two domains:

$Imported_csv | ForEach-Object {

$UserDN = $null
$TargetOU = $Null
$Server= $null

# Retrieve Username Address of user.
$User = $_.UserName

# Retrieve E-mail Address of User
$Email = $_.Email

# Retrieve DN of user based on e-mail address
$UserDNxxx  = (Get-ADUser -Server xxx -Filter {mail -eq $Email}).distinguishedName 
$UserDNxxx = (Get-ADUser -Server xxx -Filter {mail -eq $Email}).distinguishedName

# Retrieve DN of user based on Username address
$UserDNxxx  = (Get-ADUser -Server xxx -Identity $_.UserName).distinguishedName
$UserDNxxx  = (Get-ADUser -Server xxx -Identity $_.UserName).distinguishedName

Any tips would be greatly appreciated.

1
How did you define $Importedcsv? - Nico Nekoru
Sounds like a job for If. If the username has a value, use that. Otherwise, try email address. - Gabriel Luci
So, you know what you need to do, you've already put a script together - what's the question? :) - Mathias R. Jessen
Apologies - I should have been more clear. $Importedcsv being defined as follows: $import = $DataSource+"\Disable Users.csv" $Imported_csv = Import-Csv -Path $import I do believe an If statement is the answer. But my Powershell experience is very limited and I'm not entirely sure/confident how to construct it properly. - Nick Francis

1 Answers

1
votes

Sounds like you just need an If block:

If ($_.UserName) {
    # Username has a value
    $UserDNxxx  = (Get-ADUser -Server xxx -Identity $_.UserName).distinguishedName
} elseif ($_.Email) {
    # Email has a value
    $UserDNxxx = (Get-ADUser -Server xxx -Filter {mail -eq $_.Email}).distinguishedName
} else {
    # It doesn't have either, so throw an error if you want
}