Powershell, if and elseif, and blank csv fields
Hi everyone.
This one has me scratching my head.
I have a csv file called logonscripts.csv which looks like
| Name | Company_3LC | Office_3LC | Department_3LC |
| ------------ | ----------- | -----------|--------------- |
| common.bat | CY1 | LON | |
| accounts.bat | CY1 | LON | ACC |
| other.bat | CY2 | MAN | ITS |
The idea is for the code to read through the CSV and select the relevant .bat file depending on company, location and optionally the department.
My code is currently this:
$logonscripts = Import-Csv "$($datadir)\logonscripts.csv"
foreach($logonscript in $logonscripts){
if($UserCompany3LC -eq $logonscript.Company_3LC -and $UserOffice3LC -eq $logonscript.Office_3LC -and $logonscript.Department_3LC -eq "" -and $UserDepartment3LC -ne $logonscript.Department_3LC){
$UserLogonScript = $logonscript.Name
Write-Host "Blank Department?"
Write-Host "Company 3LC = "$logonscript.Company_3LC
Write-Host "Office 3LC = "$logonscript.Office_3LC
Write-Host "Department 3LC = "$logonscript.Department_3LC
Write-Host "Logon Script = "$logonscript.Name
}
elseif($UserCompany3LC -eq $logonscript.Company_3LC -and $UserOffice3LC -eq $logonscript.Office_3LC -and $UserDepartment3LC -eq $logonscript.Department_3LC){
$UserLogonScript = $logonscript.Name
Write-Host "Not Blank Department?"
Write-Host "Company 3LC = "$logonscript.Company_3LC
Write-Host "Office 3LC = "$logonscript.Office_3LC
Write-Host "Department 3LC = "$logonscript.Department_3LC
Write-Host "Logon Script = "$logonscript.Name
}
}
but when I run it, it doesn't behave as I would expect:
Not Blank Department?
Company 3LC = CY1
Office 3LC = LON
Department 3LC = ACC
Logon Script = accounts.bat
Blank Department?
Company 3LC = CY1
Office 3LC = LON
Department 3LC =
Logon Script = common.bat
If I were to append something like
else{
$UserLogonScript = $null
}
after the elseif statment the variable would output as blank!
I have a couple of questions:
Why would both if and elseif output in the console if elseif should only run if the previous if statement is FALSE?
How come the output lists Not Blank Department? first when it is listed second in the elseif statement?
Any advice would be greatly appreciated.
$UserCompany3LCcoming from? The variable would have to be assigned to before you conditional statements to$nullagain so it doesn't hold value:$UserLogonScript = $null; if (...) {...} elseif (....ifandelseifbocks are mutually exclusive - there must be something else going on that the code in the question doesn't show. The order in which the blocks execute in successive calls solely depends on which condition matches first.