Powershell to delete all local profiles, except

I am looking for a startup script thiat I can use to delete all local profiles except those belonging to key users, system accounts.  I found
(Get-WmiObject Win32_UserProfile | Where {$_.LocalPath - ‘*\TESTUSER*’}).Delete()

Open in new window

But I want these profiles to remain:
Public
All Users
AV Service
.Net AppPool
etc
LVL 8
brittonvAsked:
Who is Participating?
 
TehzarCommented:
For Instance, Line 62   '," should be ','
0
 
Chris MillardCommented:
There's a free MS Util that might be what you're looking for...

http://www.microsoft.com/download/en/details.aspx?id=5405
0
 
brittonvAuthor Commented:
How does that exclude my profiles that I want to keep?
0
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

 
TehzarCommented:
Hi Brittony,

Have a look at this article:

http://learn-powershell.net/2011/01/27/use-powershell-to-remove-local-profiles/


hth,

ZaR
0
 
brittonvAuthor Commented:
Thanks, but how do I change that code to excluede the profiles I mentioned?
0
 
TehzarCommented:
Replace original line 55 to end. Note Exclude array to avoid deleting your special profiles. This works for me on Win7 x64 but please test it to determine if it works for you!

#Cache the number of users
$num_users = $users.count 

Write-Host -ForegroundColor Green “*** There are $num_users User profiles on $computer” 

#Iterate through all of the accounts to display All User Names
For ($i=0;$i -lt $num_users; $i++) {
Write-Host -ForegroundColor Black “$($i): $(($users[$i].localpath).replace(‘C:\Users\’,”))”
}

Write-Host -ForegroundColor Green “`n*** `n*** Begin Delete of User Profiles not on Exclude List `n***”
$ExcludeList = “ProfileA”, “ProfileB”, “ProfileC”
Write-Host “*** There are $Num_Users User Profiles”
[int] $Beg_No = Read-Host “*** Enter Beginning User number”
[int] $End_No = Read-Host “*** Enter Ending user number”
Write-Host “*** User Profiles from $Beg_No to $End_No are to be deleted`n ”
if ($Beg_No -lt 0) { Write-Host “+++ Error – Beginning number less than zero”; Return}
$Limit = $Num_Users – 1
if ($End_No -gt $Limit) {Write-Host “+++ Error – Ending number GT number of profiles”; return }
$End_No = $End_No + 1

#Loop to Delete users in specified range except those on Exclude List
For ($i = $Beg_No; $i -lt $End_No; $i++) {
$test = $(($users[$i].localpath).replace(‘C:\Users\’,”))
if ($ExcludeList -contains $test) { Write-Host “`n+++ Profile $i $test will not be deleted” }
else
{ $account = $i
Write-Host -ForegroundColor BLUE “`n*** Profile $i $test to be Deleted ”
#Remove the local profile 

($users[$account]).Delete() ;
$Curr_Date = get-date -format g
Write-Host -ForegroundColor BLUE “*** Profile $i $(($users[$account].localpath).replace(‘C:\Users\’,”)) has been deleted $Curr_Date”
$Tmp = “C:\Users\” + $Test
if (test-path -path $tmp) {write-host -ForegroundColor BLUE “+++ Clean-up $Tmp”; Remove-Item -Recurse -Force $Tmp}
}
}

Write-Host “`n*** `n*** Completed `n***”
RETURN

Open in new window

0
 
brittonvAuthor Commented:
I am getting:
 
The string starting:
At C:\Users\brittonV\AppData\Local\Temp\be104650-31a6-44bf-9c5c-37a609c5dfba.ps1:59 char:44
+ ($users[$i].localpath).replace(‘C:\Users\’, <<<< ”)
is missing the terminator: ".
At C:\Users\BrittonV\AppData\Local\Temp\be104650-31a6-44bf-9c5c-37a609c5dfba.ps1:59 char:46
+ ($users[$i].localpath).replace(‘C:\Users\’,”) <<<< 
    + CategoryInfo          : ParserError: ():String) [], ParseException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
0
 
TehzarCommented:
Here's the full code.  Be sure when you copy/paste some of the apostrophes don't turn into quotes or vice versa.


<#
.SYNOPSIS
    Interactive menu that allows a user to connect to a local or remote computer and remove a local profile.
.DESCRIPTION
    Presents an interactive menu for user to first make a connection to a remote or local machine.  After making connection to the machine,
    the user is presented with all of the local profiles and then is asked to make a selection of which profile to delete. This is only valid
    on Windows Vista OS and above for clients and Windows 2008 and above for server OS.
.NOTES
    Name: Remove-LocalProfile
    Author: Boe Prox
    DateCreated: 26JAN2011
.LINK   

http://boeprox.wordpress.com

http://msdn.microsoft.com/en-us/library/ee886409%28v=vs.85%29.aspx

.EXAMPLE
Remove-LocalProfile 

Description
-----------
Presents a text based menu for the user to interactively remove a local profile on local or remote machine.
#>  

#Prompt for a computer to connect to
$computer = Read-Host "Please enter a computer name"
#Test network connection before making connection
If ($computer -ne $Env:Computername) {
    If (!(Test-Connection -comp $computer -count 1 -quiet)) {
        Write-Warning "$computer is not accessible, please try a different computer or verify it is powered on."
        Break
        }
    }
Try {
    #Verify that the OS Version is 6.0 and above, otherwise the script will fail
    If ((Get-WmiObject -ComputerName $computer Win32_OperatingSystem -ea stop).Version -lt 6.0) {
        Write-Warning "The Operating System of the computer is not supported.`nClient: Vista and above`nServer: Windows 2008 and above."
        Break
        }
    }
Catch {
    Write-Warning "$($error[0])"
    Break
    }
Do {
#Gather all of the user profiles on computer
Try {
    [array]$users = Get-WmiObject -ComputerName $computer Win32_UserProfile -filter "LocalPath Like 'C:\\Users\\%'" -ea stop
    }
Catch {
    Write-Warning "$($error[0]) "
    Break
    }
#Cache the number of users
$num_users = $users.count

Write-Host -ForegroundColor Green “*** There are $num_users User profiles on $computer”

#Iterate through all of the accounts to display All User Names
For ($i=0;$i -lt $num_users; $i++) {
Write-Host -ForegroundColor Black “$($i): $(($users[$i].localpath).replace(‘C:\Users\’,”))”
}

Write-Host -ForegroundColor Green “`n*** `n*** Begin Delete of User Profiles not on Exclude List `n***”
$ExcludeList = “ProfileA”, “ProfileB”, “ProfileC”
Write-Host “*** There are $Num_Users User Profiles”
[int] $Beg_No = Read-Host “*** Enter Beginning User number”
[int] $End_No = Read-Host “*** Enter Ending user number”
Write-Host “*** User Profiles from $Beg_No to $End_No are to be deleted`n ”
if ($Beg_No -lt 0) { Write-Host “+++ Error – Beginning number less than zero”; Return}
$Limit = $Num_Users – 1
if ($End_No -gt $Limit) {Write-Host “+++ Error – Ending number GT number of profiles”; return }
$End_No = $End_No + 1

#Loop to Delete users in specified range except those on Exclude List
For ($i = $Beg_No; $i -lt $End_No; $i++) {
$test = $(($users[$i].localpath).replace(‘C:\Users\’,”))
if ($ExcludeList -contains $test) { Write-Host “`n+++ Profile $i $test will not be deleted” }
else
{ $account = $i
Write-Host -ForegroundColor BLUE “`n*** Profile $i $test to be Deleted ”
#Remove the local profile

($users[$account]).Delete() ;
$Curr_Date = get-date -format g
Write-Host -ForegroundColor BLUE “*** Profile $i $(($users[$account].localpath).replace(‘C:\Users\’,”)) has been deleted $Curr_Date”
$Tmp = “C:\Users\” + $Test
if (test-path -path $tmp) {write-host -ForegroundColor BLUE “+++ Clean-up $Tmp”; Remove-Item -Recurse -Force $Tmp}
}
}

Write-Host “`n*** `n*** Completed `n***”
RETURN

Open in new window

0
 
brittonvAuthor Commented:
thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.