Advertisement
Guest User

Remove-UserProfile

a guest
Oct 21st, 2014
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function Remove-UserProfile{
  2.             <#
  3.         .SYNOPSIS
  4.             Removes User Profiles from a machine via WMI
  5.         .Description
  6.             This Cmdlet is used to remove user profiles from a machine when it is inconveinient to do so from the System menu. The script relies on Cmdlet Get-UserProfile. It is especially userful on Terminal Server/RDS machines where opening the system menu to delete user profiles can take hours (because reasons, I suppose).
  7.         .PARAMETER UserID
  8.             UserID to search for. Unlike Get-UserProfile, this cannot be left blank. If you intentionally want to remove all user profiles, or need to select multiple, you can use WMIs limited regex. Check this Link for more information: http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/13/use-the-like-operator-to-simplify-your-wql-queries.aspx
  9.         .PARAMETER Computer
  10.             Computer to delete user accounts from. Leaving Blank will default to 'localhost'.
  11.         .PARAMETER Batch
  12.             This Flag will suppress confirmation dialogs, as well change console output to the more redirect friendly Write-Output, rather than the Write-Host it otherwise uses.
  13.         .PARAMETER OlderThan
  14.             Filter user accounts based on last use time. Remember that this Cmdlet does not assume 'all users', so you must specify -UserID %.
  15.         .Example
  16.             Remove-UserProfile myuser remotemachine.mydomain.com
  17.             Remove Users using positional parameters
  18.         .Example
  19.             Remove-UserProfile -UserID myuser -Computer remotemachine.mydomain.com
  20.             remove users specifying with flags
  21.         .Example
  22.             Get-Content machinelist.txt | % {Remove-UserProfile -User myuser -Computer $_ -Batch} >> C:\Temp\UserRemoval.log
  23.             Remove a user from a list of machines using the batch mode, seding output to a log file
  24.         .Example
  25.             Remove-UserProfile -OlderThan $((get-date).adddays(-14)) -UserID %
  26.             Remove all user accounts that haven't been used in 14 days
  27.             The '%' here is the WMI regex for anything (analogous to '*' (or '.*') in most regex) -- it is necessary because this Cmdlet never assumes all users
  28.  
  29.         .Notes
  30.             Author: Keith Ballou
  31.             Date: Oct 16, 2014
  32.          #>
  33.  
  34.     [CmdletBinding()]
  35.     param(
  36.         [Parameter(Mandatory=$True)][string]$UserID,
  37.         [Parameter(Mandatory=$False)][string]$Computer="LocalHost",
  38.         [Parameter(Mandatory=$False)][datetime]$OlderThan=(get-date).adddays(1),
  39.         [Parameter(Mandatory=$False)][switch]$Batch
  40.  
  41.     )
  42.  
  43.     #Make Sure Necessary Cmdlets Exist
  44.     if(!(Get-Command Get-UserProfile -ErrorAction SilentlyContinue)){
  45.     write-host -BackgroundColor "Black" -ForegroundColor "Red" "################################################################################"
  46.     write-host -BackgroundColor "Black" -ForegroundColor "Red" "#                                                                               "
  47.     write-host -BackgroundColor "Black" -ForegroundColor "Red" "This Program Requires cmdlet ""Get-UserProfile""                                "
  48.     write-host -BackgroundColor "Black" -ForegroundColor "Red" "Find it here:                                                                   "
  49.     write-host -BackgroundColor "Black" -ForegroundColor "Red" "http://pastebin.com/wvUDki7p                                                    "
  50.     write-host -BackgroundColor "Black" -ForegroundColor "Red" "#                                                                               "
  51.     write-host -BackgroundColor "Black" -ForegroundColor "Red" "################################################################################"
  52.     break;
  53.     }
  54.  
  55.     #to simplify query, if OlderThan was not specified, assume anything earlier than right now (plus a day to account for timezones, rounding, etc)
  56.     #if(![bool]$OlderThan){
  57.      #   $OlderThan = (get-date).adddays(1)
  58.     #}
  59.  
  60.     #This Part relies on another of my Cmdlets "get-UserPorfile" to simplify the code a bit
  61.     #This Could be substituted with: $ProfileList = Get-WmiObject -Computer $Computer -Query "Select * From Win32_UserProfile where LocalPath like \\$UserID"
  62.     #..............................: $ProfileList = $ProfileList | Where-Object -Property Special -eq $False
  63.     #Additional logic may have to be added if WMI doesn't like 'localhost' as a ComputerName. Seems to work ok for me, but I wouldn't count on it.
  64.     #Get_UserProfile includes this logic
  65.     $ProfileList = Get-UserProfile -Verbose -UserID $UserID -Computer $Computer -ExcludeSystemAccounts -OlderThan $OlderThan
  66.  
  67.  
  68.     #If no Users were found, exit
  69.     if(!$ProfileList){
  70.         Write-Warning "NO USER PROFILES WERE FOUND"
  71.         RETURN;
  72.     }
  73.  
  74.     #Confirmation Dialog if -Batch is not set
  75.     if(!$Batch){
  76.         Write-Warning "ABOUT TO REMOVE THE FOLLOWING USER ACCOUNTS"
  77.         Foreach($User in $ProfileList){
  78.             $User | Select SID,LocalPath,@{Label="Last Use Time";Expression={Convert-UTCtoDateTime $_.LastUseTime -ToLocal}}
  79.         }
  80.         $Title = "PROCEED?"
  81.         $Message = "ARE YOU SURE YOU WANT TO REMOVE THE LISTED USER ACCOUNTS?"
  82.         $Yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes","Removes User Accounts"
  83.         $No = New-Object System.Management.Automation.Host.ChoiceDescription "&No","Exits Script, No Changes Will be Made"
  84.         $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
  85.         $result = $host.ui.PromptForChoice($title, $message, $options, 1)
  86.         switch ($result)
  87.         {
  88.             0 {}
  89.             1 {return;}
  90.         }
  91.  
  92.     }
  93.  
  94.     #Remove Users provided they are not currently Loaded
  95.     Foreach($User in $ProfileList){
  96.         if($User.Loaded){
  97.             if(!$Batch){
  98.             Write-Host -BackgroundColor "Black" -ForegroundColor "Red" "User Account " $User.LocalPath "is Currently in user on" $Computer ":`tSkipping"
  99.             }
  100.             else{
  101.             Write-Output "User $($User.LocalPath) on $($Computer) was in use and could not be removed"
  102.             }
  103.             continue;
  104.         }
  105.         if(!$Batch){
  106.         Write-Host -BackgroundColor "Blue" -ForegroundColor "Green" "Removing User $($UserID.LocalPath) from $($Computer)"
  107.         }
  108.         else{
  109.         Echo "Deleting $($User.LocalPath) from $($Computer)"
  110.         }
  111.         $User.delete()
  112.  
  113.  
  114.     }
  115.  
  116. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement