Home > Enterprise >  I'm trying to see the result of this script, when it runs it closes right away and doesn't
I'm trying to see the result of this script, when it runs it closes right away and doesn't

Time:11-05

This is my script,

I'm trying to add a user to these groups and show the result at the end to which group the user are in.

$user =  Read-host "Please enter user"
$groups = 'M365-E3-Laptop-Office-Desktop','M365-E3-Laptop-EXO'
$groupsremove = 'M365-F3-WebOnly-Apps'

foreach($group in $groups){
  Add-ADGroupMember -Identity $group -Members $user}

foreach($groupsremove in $groupsremove){
  Remove-ADGroupMember -Identity $groupsremove -Members $user}

foreach($user in $groups){
  Get-ADPrincipalGroupMembership $user | select name} 

Start-Sleep -seconds 30

CodePudding user response:

try this, maybe its case sensitive

$user =  Read-host "Please enter user"
$groups = 'M365-E3-Laptop-Office-Desktop','M365-E3-Laptop-EXO' $groupsremove = 'M365-F3-WebOnly-Apps'

foreach($group in $groups){ Add-ADGroupMember -Identity $group -Members $user}

foreach($groupsremove in $groupsremove){ Remove-ADGroupMember -Identity $groupsremove -Members $user}

foreach($user in $groups){Get-ADPrincipalGroupMembership $user | select name} 

Start-Sleep -Seconds 30`

CodePudding user response:

First, there is no need to use ForEach instruction if your variable $groupsremove only contains one group. Second, there is also no need to use ForEach instruction since you only have one user.

$user =  Read-host "Please enter user"
$groups = 'M365-E3-Laptop-Office-Desktop','M365-E3-Laptop-EXO'
$groupsremove = 'M365-F3-WebOnly-Apps'

ForEach($group in $groups)
{
    Add-ADGroupMember -Identity $group -Members $user
}

Remove-ADGroupMember -Identity $groupsremove -Members $user

Get-ADPrincipalGroupMembership $user | Select-Object Name

It should returns you something like this:

Name
----
M365-E3-Laptop-Office-Desktop
M365-E3-Laptop-EXO

Then, regarding the powershell prompt closing after the script is finished, you could simply call the script through a PowerShell prompt first instead of executing the script directly from the file, so the window doesn't close at the end.

  • Related