Functions/Public/Start-COVPermSep.ps1

#Adding user to remote desktop group
function Start-COVPermSep {
    <#
.SYNOPSIS
    This Cmdlet will run through the seperation process for city employees
.DESCRIPTION
    Use this cmdlet when you receive a user separation ticket, this command will handle the following steps.
 
           Reset Password
        Move to Separated Users OU
           Backup Groups to csv file located in \\internal\infotech\_TechniciansWorkgroup\Group Memberships
        Remove the user from all security groups except Domain Users
        Change the users AD description to Completed on <Todays Date> - <Initials>
 
.PARAMETER User
     Supply the AD user account name in this field
.PARAMETER Initials
    Supply this parameter to sign off that you are running the script. It also is used to show the completed date in the users AD account
 
.NOTES
    To use the function you will need to supply two parameters that are mandatory, These are -User and -Initials. The command will not run without these parameters
    The User parameter is pretty straightforward, supply the username of the user who is leaving. As for the initials, supply your own initials. This will mark your
    initials in the AD users description and in the end result log file.
.LINK
https://github.com/DrDad0217/COVHelp/blob/main/Start-COVPermSep.md
     
.EXAMPLE
    Start-COVPermSep -User Schmidtt -Initials TS
    This command would run the separation process on the AD user 'Schmidtt' Be sure to supply your initials in the initials parameter.
     
#>



    [CmdletBinding()]
    param (
        # Last Name of user
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]
        $User,
        # First Name of user
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]
        $Initials
    )

    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 

    #Used later to add RDP permissions to the techs test machine
    switch ($Initials) {
        TS { $TestPC = 'INT012055T' }
        KA { $TestPC = 'INT012720T' }
        KP { $TestPC = 'INT012047T' }
        TR { $TestPC = 'INT011876T' }
        CG { $TestPC = 'INT012028T' }
        JH { $TestPC = 'INT012581T' }
     
        Default {}
    }

    
    $ConfirmComp = Read-Host -Prompt "The entered username is referencing $(get-aduser $user | select -ExpandProperty Name), is this correct? (y/n)"

    if ($ConfirmComp -eq 'y') {

        Write-Verbose "Performing new user seperation for $name" 

        
    }
    else {
        while ($ConfirmComp -eq 'n') {
            
            $User = Read-Host "Enter the username of the user you Would like to run the seperation script against "
            $username = Get-Aduser $User 
            $Full = $username.name
            $ConfirmComp = Read-Host -Prompt "The entered username is referencing $Full , is this correct? (y/n)"

        }
    }

    if ($ConfirmComp -eq 'y') {

        Write-Verbose "Performing new user separation for $full" 

        
    }


    ##############
    ## Log File ##
    ##############

    $Date = Get-Date -Format MM-dd-yyyy 
    $Logname = $User + '-' + $Date + '.txt'
    $LogFile = "\\cvfile01\software\Apps\_NoAppScripts\Powershell\Scriptlogs\UserSeparation\$Logname" 
    New-Item $LogFile -Force

    $ErrorLogname = $User + '_Errors.txt'
    $ErrorLogFile = "\\cvfile01\software\Apps\_NoAppScripts\Powershell\Scriptlogs\User_Separation_Errors\$ErrorLogname" 
    New-Item $ErrorLogFile -Force


    #########################
    ## AD Password Reset ##
    #########################

    $Capital = [char[]] (Get-Random -input $(65..90) -Count 1) -join ""
    $Small = [char[]] (Get-Random -input $(97..122) -Count 1) -join ""
    $Small2 = [char[]] (Get-Random -input $(97..122) -Count 1) -join ""
    $Number = [char[]] (Get-Random -input $(48..57) -Count 1) -join ""
    $Number2 = [char[]] (Get-Random -input $(48..57) -Count 1) -join ""
    $Number3 = [char[]] (Get-Random -input $(48..57) -Count 1) -join ""
    $Number4 = [char[]] (Get-Random -input $(48..57) -Count 1) -join ""
    $Number5 = [char[]] (Get-Random -input $(48..57) -Count 1) -join ""

    $Password = $Capital + $Small + $Small2 + $Number + $Number2 + $Number3 + $Number4 + $Number5

    [System.Windows.Forms.Clipboard]::SetText($Password)

    $Password | ConvertTo-SecureString -AsPlainText -Force

    Add-Type -AssemblyName PresentationFramework

    $Passbox = [System.Windows.MessageBox]::Show("The users new password has been copied to your clipboard.", 'Dont lose me!', 'Ok')


    $Newpassword = $password | ConvertTo-SecureString -AsPlainText -force #Converts password to secure string

    Set-ADAccountPassword -Identity $User -NewPassword $Newpassword 

    ############################
    ## Security Group Backup ##
    ############################

    #CSV file name
    $FILENAME_FORMAT = $(Get-ADUser -Identity $User).name.split() + "_" + (Get-Date -Format MMddyyyy) -join '' -replace ",","-"
    #CSV file path
    $GM_LOG = "\\internal\infotech\_TechniciansWorkgroup\Group Memberships\$FILENAME_FORMAT.csv"

    try {

        Get-ADPrincipalGroupMembership -Identity $User | Where { $_.Samaccountname -ne "Domain users" } | Select SamAccountName | Sort SamAccountName | Export-Csv -Path $GM_LOG -NoTypeInformation

        Add-Content $LogFile -Value "Security groups have been exported successfully to $GM_LOG"
    
    }
    catch {

        Write-Error "Export of user's security groups have failed."
    
    }




    ############################
    ## Security group removal ##
    ############################

    $Groups = Get-ADPrincipalGroupMembership -Identity $User | Where { $_.Samaccountname -ne "Domain users" } | Select SamAccountName | Sort SamAccountName

    try {

        foreach ($SG in $Groups.Samaccountname) {

            Remove-ADGroupMember -Identity $SG -Members $User -Confirm:$false -ErrorAction Stop

            Add-Content $LogFile -Value "User has been Sucessfully removed from $SG"
    
        }
    }
    catch {

        Write-Error $_
    
    }



    #################################
    ## Move to Separated Users OU ##
    #################################


    try {
        Get-Aduser -Identity $User | Move-ADObject -TargetPath 'OU=Separated Employees,OU=IT Support Accounts,DC=internal,DC=cityofvancouver,DC=US' 

    }
    catch {

    
    

        Write-Error $_.Exception.Message 
    
    }
    finally {

        Add-Content $ErrorLogFile -Value $Errorvalue
        
    
    }


    try {
    
        Get-ADUser -Filter * -SearchBase "OU=Separated Employees,OU=IT Support Accounts,DC=internal,DC=cityofvancouver,DC=US"  | Where-Object { $_.SamAccountName -match $User } 

        Add-Content $LogFile -Value "$User has been successfully moved to the Separated Users OU"
    
    }
    catch {

        Write-Error $_ -OutVariable Errorcheck

    
    }
    finally {

        Add-Content $ErrorLogFile -Value $Errorcheck
    
    }

 
    #############################
    ## Set AD User Description ##
    #############################

    $Description = 'Completed' + ' ' + $Date + ' ' + '-' + $Initials

    Set-ADUser -Identity $User -Description $Description

    #Enable account if its disabled
    If (-not(Get-Aduser -Identity $User | Where Enabled -EQ 'True')) {

        Set-ADUser -Identity $User -Enabled $true -Verbose
        
    }    
    
    #Clearing account expiration
    Clear-ADAccountExpiration -Identity $User -Verbose
      

    #####################
    ## Log File Invoke ##
    #####################

    Add-Content $LogFile "User Description has been changed to Completed $Date $Initials"


    #####################
    ## Check Homepath ##
    #####################

    $Total = dir -path $HomeDir -file -force -ErrorAction Continue | 
    Measure-object length -sum -max -average | 
    Select-Object @{name = "Total Files"; Expression = { $_.count } },
    @{name = "Largest File(MB)"; Expression = { "{0:F2}" -f ($_.maximum / 1MB) } },
    @{name = "Average Size(MB)"; Expression = { "{0:F2}" -f ($_.average / 1MB) } },
    @{name = "Total Size(MB)"; Expression = { "{0:F2}" -f ($_.sum / 1MB) } }

    $HomeDir = (Get-Aduser $User -Properties *).HomeDirectory

    if ($Total.'Total Size(MB)' -eq $Null -or $Total.'Total Size(MB)' -lt 50) {

        Add-Content $Logfile "The users G Drive is under 50KB, there is no need to back up their files to Onedrive"

    }
    else {

        Add-Content $Logfile -Value "The size of the users G Drive is currently $($Total.'Total Size(MB)')MB, the users data needs to be backed up. " 
    }
     

    
    # Adds user to the technicians test machine
    $ConfirmCompPC = Read-Host -Prompt "Would you like to grant the user Remote Access to your test machine? (y/n)"

    if ($ConfirmCompPC -eq 'y') {
 
        Invoke-Command -ComputerName $TestPC -ScriptBlock {

            Add-LocalGroupMember -Group (Get-LocalGroup | Where name -Match 'Remote desktop') -Member $Using:User 
        }

    }

    $Permission_Check = Invoke-Command -ComputerName $TestPC -ScriptBlock { Get-LocalGroupMember -Group 'Remote Desktop Users' | Where name -Match $Using:User }

    if ($Permission_Check.name -match $User) {

        Add-Content -Path $Logfile -Value "$using:User has been added to the RDP Users group on $using:TestPC" 
    }
    else {
        
        #Add-Content -Path $Logfile -Value "$Unable to add $User to RDP Users group on $TestPC GL Broski you're on your own"
        
        
    }
    
    
    #Departments who hold RSA Tokens
    $Depts = 'Information Technology', 'Police', "City Attorney's Office"

    if ($Depts -contains (Get-aduser -Identity $User -Properties *).department ) {

        $ConfirmCompVPD = Read-Host -Prompt "Have you removed the RSA token for the Police officer? (y/n)"
   
        while ($ConfirmCompVPD -ne 'y') {
   
            Write-Output "Well then get to it!"
            $ConfirmCompVPD = Read-Host -Prompt "Have you removed the RSA token for the User? (y/n)"
   
        }
   
    }
    
    Add-Content $LogFile "Script was ran by $Initials on $Date"
    
    Invoke-Item $LogFile
}