Function for disabling or deleting users

Viewed 41

Hi I am working on a function that either deletes or disables a user in AD, by specifying either the Remove or disable parameter. If the parameters are set to true, the action should be performed. When I run my script it find the User and outputs it, when it comes to the disable block it prompts me for user Identity and disables the user when specifying it in the Command window.

I am new to PowerShell functions, can anyone tell me where am going wrong?

function Remove-User{
param(
[Parameter(Mandatory=$true)][string]$User,
[bool]$Remove,
[bool]$Disable
)

if (Get-ADUser -Filter {SamAccountName -eq $User})
{    Write-Output $User
     if($Disable = $true){
        
         Set-ADUser -SamAccountName $User -Enabled $false
    }
    elseif($Remove = $true){
     Remove-ADUser -Identity $User
    }
    else{
        Write-Output "Done"
    }
}

else{
    Write-Output "User doesn't exist"
}
}
       
   Remove-User -User "TT" -Disable $true
1 Answers

Seems like you're looking to have a function that can perform one of both actions but not both at the same time, if that's the case, it might be a good idea to have just one parameter (-Action) that uses a ValidateSet attribute declaration. In addition, since both actions you want to perform can have high impact in Active Directory, it might be a good idea to use ConfirmImpact set to High so the function always prompts for confirmation unless -Confirm:$false.

function Remove-User {
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
    param(
        [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
        [string] $Identity,

        [Parameter(Mandatory)]
        [ValidateSet('Disable', 'Remove')]
        [string] $Action
    )

    process {
        if($PSCmdlet.ShouldProcess([string] $Identity, $Action)) {
            try {
                if($Action -eq 'Disable') {
                    return $Identity | Disable-ADAccount
                }
                $Identity | Remove-ADUser
            }
            catch {
                $PSCmdlet.WriteError($_)
            }
        }
    }
}

Now when calling the function only one "Action" will be available:

demo

And the function will prompt for confirmation by default unless -Confirm:$false is used:

PS /> Remove-User john.doe -Action Remove

Confirm
Are you sure you want to perform this action?
Performing the operation "Remove" on target "john.doe".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

Also, -WhatIf becomes a possibility when the function SupportsShouldProcess:

PS /> 'john.doe', 'jane.doe' | Remove-User -Action Disable -WhatIf

What if: Performing the operation "Disable" on target "john.doe".
What if: Performing the operation "Disable" on target "jane.doe".
Related