So I am writing a powershell script that, among other things, checks to see if you are in an Exchange Distribution Group, and adds you if necessary.
One thing that is making it tricky is, the script is getting its data from an "unreliable" source. That is, I can't guarantee that I have a username to even check against.
So, I need to check in the case of an empty string. I have my username stored in a variable $tempUserName
which is just a String, and the name of a Distribution List stored in $DefaultMobileDL
. For other reasons I won't get into, I can't do if {} else {}
statements, I can only do if statements. It is very stupid, I know.
OK, so here is what I have:
if (-not [string]::IsNullOrEmpty($tempUsername)) {
$MembersOfDLDefault = Get-DistributionGroupMember "$DefaultMobileDL" -ResultSize Unlimited |
Select -Expand sAMAccountName |
Select-String -pattern "$tempUsername" -SimpleMatch -Quiet
}
if ([string]::IsNullOrEmpty($tempUsername)) { $MembersOfDLDefault = $false }
# bug testing...
Write-Host "username: `"$tempUsername`" , MembersOfDLDefault: `"$MembersOfDLDefault`""
if ($MembersOfDLDefault -eq $false) {
# User is not a member of $DefaultMobileDL, try adding them
# ... more code here ...
}
if ($MembersOfDLDefault -eq $true) {
# User is already a member of the $DefaultMobileDL
# ... again, more code ...
}
That code block is in a foreach loop, and since I was having problems with variables values being passed on after each iteration, at the very end of my code I clear several variables, but for this instance the one line that matters is:
Clear-Variable MembersOfDLDefault
Now if I'm reading the documentation right, Select-String -Quiet
should return True if the item was found, and False if it wasn't.
However, that is not the results that I'm getting. Here is what happens when I run the code (in this run, I have 3 usernames I happen to be testing, one of which (the third one) is an empty string):
username: "smithj" , MembersOfDLDefault: ""
username: "doej" , MembersOfDLDefault: "True"
username: "" , MembersOfDLDefault: "False"
As you can see, the first time the code is run, $MembersOfDLDefault
doesn't get set to anything!
I know I'm just missing something stupid, but I've been staring at this code for too long, need some fresh eyes on it. Anything obvious that I'm missing or overlooking?
Thanks in advance.
Technically I'm running this from the Exchange Management Shell, and not from Powershell directly, although I don't think that should matter