I am having difficulty using an if statement with blank cells in my CSV file. I'm attempting to write an onboarding script and have it pull info from an xlsx HR fills out (IT copies needed rows into CSV that is used in script). In order to get the OU path, I use the department names. However, some users have a sub-department and others do not, these fields are left blank in the xlsx that HR sends. I have it working by inputting a N/A in those fields however if another tech doesn't know to do that in the CSV file the script will fail. So I would like to get it working with the blank fields.
This is what im trying when not using the N/A in the CSV field
foreach ($obj in $onboardcsv){
$dep = "$($obj.department)"
$sdep = "$($obj.subDepartment)"
if ($null -eq $obj.subDepartment){
$ou = Get-ADOrganizationalUnit -Filter {name -like $dep} -SearchBase "OU=User,OU=OU,DC=DOMAIN,DC=com"
}
else{
$ou = Get-ADOrganizationalUnit -Filter {name -like $sdep} -SearchBase "OU=User,OU=OU,DC=DOMAIN,DC=com"
}
Any help would be appreciated!
CodePudding user response:
To rephrase your question, you just want to search where SubDepartment isn't empty?
Without modifying too much of your code, you can make use of the static method of ::IsNullOrWhiteSpace()
provided in the [string]
class to evaluate against the emptiness:
- Using
-Not
reverses the result of[string]::IsNullOrWhiteSpace($obj.subDepartment)
.
foreach ($obj in $onboardcsv)
{
$department = if (-not [string]::IsNullOrWhiteSpace($obj.subDepartment)) {
$obj.subDepartment
}
else {
$obj.department
}
Get-ADOrganizationalUnit -Filter "Name -like '$department'" -SearchBase "OU=User,OU=OU,DC=DOMAIN,DC=com"
}
So, testing against the subDepartment first, if $obj.subDepartment
is not null, assign it to $department
. This will allow the use of just one variable for both properties, and no code copying necessary.
Thanks to @Santiago for a sanity check.
CodePudding user response:
Something like this would work.
$ou = "searching by sub department"
$department = if (!($user.subDepartment)) {
#subdepartment is blank
#searching by department
$ou = "searching by department"
}
$ou