Script won't for more than one group when looking at results of whoami command
Trying to setup IF/ELSE on a script whereby it checks for two conditions to be met before the script runs:
- Check if the following file exists on the desktop. (
$FileExists
) - Check if the user is a member of only one group containing 6 digits it's group name. (
$GroupCount
)
Continue if the results of whoami /groups
yields only one result where group name contains _6digits
E.G
Mygroup_152452_152354
Do not continue if the results of whoami /groups
shows more than one result where group name contains _6digits
E.G
Mygroup1_152452_152354
Mygroup2_152453_152355
I've used -le 1 but I don't think I'm going about it the correct way? A bit stumped and would greatly appreciate if someone could help me see where it's gone wrong?
Currently, the script jumps to exit when I run it from a user that should satisfy the equal to 1 or less condition (only a member of one group containing _6digits).
$WantFile = "$env:USERPROFILE\Desktop\myfile.lnk"
$FileExists = Test-Path $WantFile
$Groups = WhoAmI /Groups /FO CSV | ConvertFrom-Csv
$GroupCount = $Groups.'Group Name'.Where{ $Groups -match '(_\d{6}){1}'} -le 1
If ($FileExists -eq $False -And $GroupCount -eq $True)
{
Write-Host "Carry on script"
}
Else {
Write-Host "Exit the script"
Exit
}
Solution 1:
Thank you Reddy Lutonadio for the guidance on this.
After testing this is what worked for me:
$WantFile = "$env:USERPROFILE\Desktop\myfile.lnk"
$FileExists = Test-Path $WantFile
$Groups = WhoAmI /Groups /FO CSV | ConvertFrom-Csv
$GroupResults = $Groups.'Group Name'.Where{ $_ -match '(_\d{6}){1}'}
If ($FileExists -eq $False -And $GroupResults.count -eq 1)
{
Write-Host "Carry on script"
}
Else {
Write-Host "Exit the script"
Exit
}
Adding .count
to the end of $GroupResults
within the If
statement allowed me to use eq 1