Home > Software engineering >  End Script when "User is already a member of group"
End Script when "User is already a member of group"

Time:09-28

I have a script I'm using to auto add domain users into a specific group. It also incorporates a stop/restart of a 3rd party service that adds them into a secure user file. I'd like for this script to end the moment it finds that the user is already a part of the group, and NOT stop/start the service. This is what I have so far:

Invoke-Command -ComputerName ServerNameHere -ScriptBlock {add-LocalGroupMember -Group "GroupNameHere" -Member $env:USERDOMAIN\$env:USERNAME }
*--Add in line here that terminates the script once user is found to already be a member and not restart the service below*
Stop-Service -Name "ServiceNameHere"
timeout /t 5 /nobreak
Start-Service -Name "ServiceNameHere"

When I run the script, I get the below message, which is normal, and then the script continues to run, thus restarting the service anyway.

Domain\User is already a member of group GroupName
      CategoryInfo          : ResourceExists: (GroupName:String) [Add-LocalGroupMember], MemberExistsException
      FullyQualifiedErrorId : MemberExists,Microsoft.PowerShell.Commands.AddLocalGroupMemberCommand
      PSComputerName        : ServerName

Thanks for all your help in advance!

CodePudding user response:

You could check the output of Invoke-Command before restarting the service:

$Result = Invoke-Command -ComputerName ServerNameHere -ScriptBlock {
  # Check whether user is already a member of group
  If ((Get-LocalGroupMember 'GroupNameHere').Name -notcontains "$env:USERDOMAIN\$env:USERNAME") {
    Add-LocalGroupMember -Group 'GroupNameHere' -Member "$env:USERDOMAIN\$env:USERNAME" 
    Write-Output $True
  }
  Else { Write-Output $False }
}

# If group membership changed, restart service:
If ($Result) {
  Stop-Service -Name "ServiceNameHere"
  timeout /t 5 /nobreak
  Start-Service -Name "ServiceNameHere"
}
  • Related