?
Solved

Powershell to delete all local profiles, except

Posted on 2011-10-24
9
Medium Priority
?
999 Views
Last Modified: 2012-05-12
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
0
Comment
Question by:brittonv
  • 4
  • 4
9 Comments
 
LVL 17

Expert Comment

by:Chris Millard
ID: 37020547
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
 
LVL 8

Author Comment

by:brittonv
ID: 37020577
How does that exclude my profiles that I want to keep?
0
 
LVL 9

Expert Comment

by:Tehzar
ID: 37024351
Hi Brittony,

Have a look at this article:

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


hth,

ZaR
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 8

Author Comment

by:brittonv
ID: 37030589
Thanks, but how do I change that code to excluede the profiles I mentioned?
0
 
LVL 9

Expert Comment

by:Tehzar
ID: 37030805
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
 
LVL 8

Author Comment

by:brittonv
ID: 37033919
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
 
LVL 9

Expert Comment

by:Tehzar
ID: 37034813
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
 
LVL 9

Accepted Solution

by:
Tehzar earned 2000 total points
ID: 37034819
For Instance, Line 62   '," should be ','
0
 
LVL 8

Author Closing Comment

by:brittonv
ID: 37121255
thanks
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The following article is intended as a guide to using PowerShell as a more versatile and reliable form of application detection in SCCM.
A recent project that involved parsing Tableau Desktop and Server log files to extract reusable user queries for use in other systems. I chose to use PowerShell to gather the data, and SharePoint to present it...
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Screencast - Getting to Know the Pipeline

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question