即使CSV中的输出在单元格中有数据$ MemberName,此if语句由于某种原因也不匹配。
if($MemberName -notlike "Administrator" -or $MemberName -notlike "Domain Admins" -or $MemberName -notlike "Workstation Admin"){
Add-Content -Path $OutPutFile -Value "$Computer, $LocalGroupName, SUCCESS, $MemberType, $MemberDomain, $MemberName"
}
还有一种更有效的方法来编写if语句吗?我只想添加行$ IF $ MemberDomain和$ MemberName不符合以下几组标准:
$MemberDomain $MemberName
LocalUser AND Administrator
DomainGroup AND Workstation Admin
DomainGroup AND Domain Admins
Somethinng喜欢:
if(($MemberName -notlike "Administrator" -and $MemberDomain -notlike "LocalUser") -or ($MemberName -notlike "Domain Admins" -and $MemberDomain -notlike "DomainGroup") -or ($MemberName -notlike "Workstation Admin" -and $MemberDomain -notlike "DomainGroup")) { do something }
这是有效的,但我认为有更有效的方法来测试这两个值。
$ExcludedNames = ("Administrator","Workstation Admin","Domain Admins")
$ExcludedMemberTypes = ("LocalUser","DomainGroup")
if(($ExcludedNames -contains $MemberName) -and ($ExcludedMemberTypes -contains $MemberType) ){
} else {
Add-Content -Path $OutPutFile -Value "$Computer, $LocalGroupName, SUCCESS, $MemberType, $MemberDomain, $MemberName"
}
我想要同时匹配的问题。例如,“DomainGroup和Administrator”的组合对于上面的代码是正确的,当只有LocalUser和Administrator应该为true时它应该是false。
答案 0 :(得分:2)
只要您不需要通配符匹配,就可以使用switch
和-notcontains
$Success = switch($MemberDomain)
{
"LocalUser" {"Administrator" -ne $MemberName}
"DomainGroup" {"Workstation Admin","Domain Admins" -notcontains $MemberName}
}
if($Success){
Add-Content # ...
}
在PowerShell 3.0及更高版本中,您还可以使用等效的-notin
运算符,可能更直观一些:
$MemberName -notin "Workstation Admin","Domain Admins"