-1

I am trying to input a user using a variable and check active directory to confirm the full name of the user and pause the script before running the next command.

The script is running the pause command before the get-aduser command - see below script

#Enter Username

$username = read-host "Username"


Get-ADUser -Filter "Name -eq '$username'" | Select-Object name, samaccountname

$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

#Removes user from groups

Get-ADPrincipalGroupMembership -Identity $username | where {$_.Name -notlike "Domain Users"} |% {Remove-ADPrincipalGroupMembership -Identity $uSername -MemberOf $_ -Confirm:$false}

write-output End

$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Maxime Franchot
  • 1,015
  • 1
  • 10
  • 24
CODFrank
  • 1
  • 4

3 Answers3

0

In my experience, Get-ADUser and similar commands can take a long time to run, possible up to 20 seconds or so. Rarely, I have found that it makes the code unusable due to some commands running before or after it. If you want to test to see if this is really the case for you, add this line in between every other line in your code:

Read-Host -Prompt "Press Enter to continue"

That way, you can test whether there is a real difference between when you put that line there, and if you don't. If there is actually a difference, you may have to look into start-sleep or wait.

Maxime Franchot
  • 1,015
  • 1
  • 10
  • 24
0

I would do something like this to have the user validate, cause i think that is what you are after, before continuing to revoke the users group membership

Write-Host "`nEnter the UserName: " -NoNewline -ForegroundColor Yellow
$UserName = Read-Host

$UserName = Get-ADUser -Filter "Name -eq '$UserName'" | Select-Object Name, SamAccountName

Write-Host "`nRevoke membership of all groups for user" $UserName.Name "("$UserName.SamAccountName")?`n [Y]es, [N]o : " -ForegroundColor Yellow -NoNewline

$Confirmation = Read-Host


While ("y","yes","n","no" -notcontains $Confirmation) {

     Write-Host "`nNot a valid input! Please try again ..." -ForegroundColor Red
     Write-Host "`nRevoke membership of all groups for user" $UserName.Name "("$UserName.SamAccountName")?`n [Y]es, [N]o : " -ForegroundColor Yellow -NoNewline

     $Confirmation = Read-Host

}

If ($Confirmation -eq "n" -or $Confirmation -eq "no") {

    Write-Host "Aborted!" -ForegroundColor Red
    Break

}

# Next step here!

# Get-ADPrincipalGroupMembership -Identity $UserName | where {$_.Name -notlike "Domain Users"} |% {Remove-ADPrincipalGroupMembership -Identity $UserName -MemberOf $_ -Confirm:$false}
Jonas
  • 164
  • 1
  • 10
0

Just another piece of code, these kind of changes needs some proper logging and error handling, while my code only logs to the console it can still be useful. It uses confirm in place of 'pause' so the user can choose to continue or stop.

### CmdletBinding
# Alows the use of -Whatif(not used), -Confirm, -Verbose and -Debug.
# Reference: https://technet.microsoft.com/en-us/library/ff677563.aspx
#            https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_functions_cmdletbindingattribute
#            https://blogs.technet.microsoft.com/poshchap/2014/10/24/scripting-tips-and-tricks-cmdletbinding/
[CmdletBinding(
    SupportsShouldProcess = $true,
    ConfirmImpact=’High’
    )]

# Script parameters.
Param(
    [parameter(HelpMessage = "Command parram, not used.")]$Command = "nothing" 
    #Run with PowerShell Fix, reference: https://social.technet.microsoft.com/Forums/office/en-US/fe7fb473-7ed6-4397-9c95-120201c34847/problems-with-powershell-30?forum=winserverpowershell
    )

#Console clean-up.
Clear-Host

# Set error action to Stop, if something happens and it isnt inside a trap (try/catch) then stop.
$ErrorActionPreference = "Stop" 

# Controls the Verbose Output
$VerbosePreference = "Continue" #Optional

#Intial message for User execution, whitespace is for the progressbars.
"









    Script: Remove-ADUserGroupMembership.ps1


"

Write-Verbose "Starting main loop."
While ($true){

    #White space for in between questions.
    Write-Host  "
    "

    #Retrieve username from user input.
    Write-Host "Provide the ADUser for ADGroup removal here:"
    $Username = read-host "Username"

    #Retrieve ADUser object from AD.
    Write-Verbose "Querying Active Directory for user $Username"
    Try {
        $ADUser = Get-ADUser $Username
        Write-Verbose "User Found, $($ADUser.Name) "
    }

    catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
        Write-Warning "Could not find user $Username in Active Directory, check spelling and try again."
        Continue #this wil reset the while loop
    }

    Catch {
        Write-Warning "Unknown Errror, Could not retrieve user $Username from Active Directory, please try again."
        Continue #this wil reset the while loop
    }

    #Retrieve GroupMembership for user.
    Write-Verbose "Querying Active Directory for GroupMembership of User $($ADUser.name), exluding Domain Users"
    Try {
        $GroupMembership = $ADUser | Get-ADPrincipalGroupMembership | where {$_.Name -notlike "Domain Users"}
        Write-Verbose "Found $($GroupMembership.count) GroupMemberships for User $($ADUser.name) (Not inluding Domain Users)"
    }

    Catch {
        Write-Warning "Unknown Errror, Could not retrieve GroupMembership for user $($ADUser.Name) from Active Directory, please try again."
        Continue #this wil reset the while loop
    }

    #Remove GroupMembership for user.
    if ($pscmdlet.ShouldProcess("$($ADUser.name)", "Remove-ADPrincipalGroupMembership {$($GroupMembership.count) Groups}")) {
        Write-Verbose "Entering GroupMembership removal loop for user $($ADUser.name)"
        Foreach ($Group in $GroupMembership) {
            Try {                
                $ADUser | Remove-ADPrincipalGroupMembership -MemberOf $Group -WhatIf -Confirm:$true                
                Write-Verbose "$Group removed from from user $($ADUser.name)"
            }

            catch  {
                Write-Warning "An Error occured, could not remove group $Group from user $($ADUser.Name)"
                Continue #this will skip this group.
            }
        }
    } 

    else {
        Write-Warning "Action Remove-ADPrincipalGroupMembership {$($GroupMembers.count) Groups} canceled for $($ADUser.name)"
    }

    Read-Host "Press Enter to exit."
    break #exit from while loop
}
SteloNLD
  • 541
  • 3
  • 12