Combining multiple comparison methods in one IF-statement in PowerShell -
so need check if field of variable equals string.
it pretty goes this:
there multiple teams can chosen field:
- team one
- team two
depending on team is, code different stuff.
the catch however, insert of team not standardized. each member of "team one" can have team 1 written in various ways: teamone / team 1 / team one/ team1 (lets these possibilities).
in code tried check using:
if($user.active -ne 0 -and $user.team.tolower() -like "team one" -or $user.team.tolower() -like "teamone" -or $user.team.tolower() -like "team1" ) { write-host "member in team 1" } #else check if in team 2,....
my code works if use -and $user.team.tolower() -like "team one")
error you cannot call method on null-valued expression
is approach i'm doing here? or there better alternative?
you cannot call method on null-valued expression
that error telling. have variable or property null , trying call method on it. if insist on using logic need test nulls first.
this specific case can avoided when understand powershell operators case-insensitive default. .tolower()
not appear needed
that being said if
statement looks valid, outside of first caveat, there better approaches "multiple potential match scenario" have here.
-contains
since trying make full match against 1 of many possibilies wrap in array use -contains
operator on comparison
if($user.active -ne 0 -and $user.team -and "team one","teamone", "team1", "team 1" -contains $user.team){}
$user.team
evaluated truthy/falsy statement last condition wont checked if $user.team
not populated or empty string
some regex
if($user.active -ne 0 -and $user.team -and $user.team -match "team\s?(one|1)"){}
use little regex see if team 1 of following
teamone team 1 team1 team 1
in either case above -and $user.team
check not required , function without it. thought should mention if needed somewhere else verify if populated easily.
Comments
Post a Comment