Deleting Profiles Remotely

Hi… Looking for a script to delete all profiles remotely

We want to clear all profiles so the machine can be used for another user. The machines will be offsite

Very new to powershell so any help would be great

Thanks

Dan

Have you searched for “Delete Profiles Powershell”?

The Script is just for local use, Need to delete from a networked machine

You can remove wmi win32_userprofile objects. There’s a group policy to do it too.

Thanks for the answer is there a full script I could copy

The link Rob referenced has your answer:

Get-WmiObject -Class Win32_UserProfile –ComputerName CLIENT1,CLIENT2 | where {$.LocalPath.split('')[-1] -eq 'Administrator.CLIENT1'} | foreach {$.Delete()}

To delete all profiles, you will want to modify to something like this so you DONT delete the System Profiles:

Get-WmiObject -ClassName Win32_UserProfile –ComputerName CLIENT1,CLIENT2 | Where-Object {!($.LocalPath -Match 'windows')} | foreach {$.Delete()}

I am thinking that nuking the system profiles might be a bad idea.

You can view all profiles as such:

(Get-WmiObject -ClassName Win32_UserProfile –ComputerName COMPUTER1).LocalPath

 

Did you try to search for the topic before you started asking?

https://adamtheautomator.com/powershell-delete-user-profile/

Thank you, Script ran without any errors but didn’t delete the profile from c:\

$Computer = Read-Host "Please Enter Computer Name: "
$user = Read-Host "Enter User ID: "

Invoke-Command -ComputerName $computer -ScriptBlock {
param($user)
$localpath = 'c:\users' + $user
Get-WmiObject -Class Win32_UserProfile | Where-Object {$_.LocalPath -eq $localpath} |
Remove-WmiObject
} -ArgumentList $user

 

This seems to work on local machines but not remote any ideas?

I have got this script to work removing 1 profile is there anyway to put exclusions in it so we can wipe all profiles except the built in accounts for example public

$Computer = Read-Host "Please Enter Computer Name: "
$user = Read-Host "Enter User ID: "

Invoke-Command -ComputerName “” -ScriptBlock {
param($user)
$localpath = 'c:\users' + “”
Get-WmiObject -Class Win32_UserProfile | Where-Object {$_.LocalPath -eq $localpath} |
Remove-WmiObject
} -ArgumentList $user

So this is nearly exactly what I need, How would I add an option for all profiles rather than deleting 1 by 1

 

#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 abovenServer: 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 “User profiles on $($computer):”

#Begin iterating through all of the accounts to display
For ($i=0;$i -lt $num_users; $i++) {
Write-Host -ForegroundColor Green “$($i): $(($users[$i].localpath).replace(‘C:\Users',’'))”
}
Write-Host -ForegroundColor Green “q: Quit”
#Prompt for user to select a profile to remove from computer
Do {
$account = Read-Host “Select a number to delete local profile or ‘q’ to quit”
#Find out if user selected to quit, otherwise answer is an integer
If ($account -NotLike “q*”) {
$account = $account -as [int]
}
}
#Ensure that the selection is a number and within the valid range
Until (($account -lt $num_users -AND $account -match “\d”) -OR $account -Like “q*”)
If ($account -Like “q*”) {
Break
}
Write-Host -ForegroundColor Yellow “Deleting profile: $(($users[$account].localpath).replace(‘C:\Users',’'))”
#Remove the local profile
($users[$account]).Delete()
Write-Host -ForegroundColor Green “Profile: $(($users[$account].localpath).replace(‘C:\Users',’')) has been deleted”

#Configure yes choice
$yes = New-Object System.Management.Automation.Host.ChoiceDescription “&Yes”,“Remove another profile.”

#Configure no choice
$no = New-Object System.Management.Automation.Host.ChoiceDescription “&No”,“Quit profile removal”

#Determine Values for Choice
$choice = [System.Management.Automation.Host.ChoiceDescription] @($yes,$no)

#Determine Default Selection
[int]$default = 0

#Present choice option to user
$userchoice = $host.ui.PromptforChoice(“”,“Remove Another Profile?”,$choice,$default)
}
#If user selects No, then quit the script
Until ($userchoice -eq 1)

The filtering can be done more efficiently. First, let’s look at all properities:

PS C:\Users\rasim> Get-CimInstance -ClassName Win32_UserProfile


AppDataRoaming                   : Win32_FolderRedirectionHealth
Contacts                         : Win32_FolderRedirectionHealth
Desktop                          : Win32_FolderRedirectionHealth
Documents                        : Win32_FolderRedirectionHealth
Downloads                        : Win32_FolderRedirectionHealth
Favorites                        : Win32_FolderRedirectionHealth
HealthStatus                     : 3
LastAttemptedProfileDownloadTime : 
LastAttemptedProfileUploadTime   : 
LastBackgroundRegistryUploadTime : 
LastDownloadTime                 : 
LastUploadTime                   : 
LastUseTime                      : 3/4/2020 8:53:56 AM
Links                            : Win32_FolderRedirectionHealth
Loaded                           : True
LocalPath                        : C:\Users\rasim
Music                            : Win32_FolderRedirectionHealth
Pictures                         : Win32_FolderRedirectionHealth
RefCount                         : 
RoamingConfigured                : False
RoamingPath                      : 
RoamingPreference                : 
SavedGames                       : Win32_FolderRedirectionHealth
Searches                         : Win32_FolderRedirectionHealth
SID                              : S-1-5-21-2370741873-3768727752-2996739931-1001
Special                          : False
StartMenu                        : Win32_FolderRedirectionHealth
Status                           : 0
Videos                           : Win32_FolderRedirectionHealth
PSComputerName                   : 

AppDataRoaming                   : Win32_FolderRedirectionHealth
Contacts                         : Win32_FolderRedirectionHealth
Desktop                          : Win32_FolderRedirectionHealth
Documents                        : Win32_FolderRedirectionHealth
Downloads                        : Win32_FolderRedirectionHealth
Favorites                        : Win32_FolderRedirectionHealth
HealthStatus                     : 3
LastAttemptedProfileDownloadTime : 
LastAttemptedProfileUploadTime   : 
LastBackgroundRegistryUploadTime : 
LastDownloadTime                 : 
LastUploadTime                   : 
LastUseTime                      : 3/4/2020 8:53:56 AM
Links                            : Win32_FolderRedirectionHealth
Loaded                           : True
LocalPath                        : C:\WINDOWS\ServiceProfiles\NetworkService
Music                            : Win32_FolderRedirectionHealth
Pictures                         : Win32_FolderRedirectionHealth
RefCount                         : 
RoamingConfigured                : False
RoamingPath                      : 
RoamingPreference                : 
SavedGames                       : Win32_FolderRedirectionHealth
Searches                         : Win32_FolderRedirectionHealth
SID                              : S-1-5-20
Special                          : True
StartMenu                        : Win32_FolderRedirectionHealth
Status                           : 0
Videos                           : Win32_FolderRedirectionHealth
PSComputerName                   : 

AppDataRoaming                   : Win32_FolderRedirectionHealth
Contacts                         : Win32_FolderRedirectionHealth
Desktop                          : Win32_FolderRedirectionHealth
Documents                        : Win32_FolderRedirectionHealth
Downloads                        : Win32_FolderRedirectionHealth
Favorites                        : Win32_FolderRedirectionHealth
HealthStatus                     : 3
LastAttemptedProfileDownloadTime : 
LastAttemptedProfileUploadTime   : 
LastBackgroundRegistryUploadTime : 
LastDownloadTime                 : 
LastUploadTime                   : 
LastUseTime                      : 3/4/2020 8:53:56 AM
Links                            : Win32_FolderRedirectionHealth
Loaded                           : True
LocalPath                        : C:\WINDOWS\ServiceProfiles\LocalService
Music                            : Win32_FolderRedirectionHealth
Pictures                         : Win32_FolderRedirectionHealth
RefCount                         : 
RoamingConfigured                : False
RoamingPath                      : 
RoamingPreference                : 
SavedGames                       : Win32_FolderRedirectionHealth
Searches                         : Win32_FolderRedirectionHealth
SID                              : S-1-5-19
Special                          : True
StartMenu                        : Win32_FolderRedirectionHealth
Status                           : 0
Videos                           : Win32_FolderRedirectionHealth
PSComputerName                   : 

AppDataRoaming                   : Win32_FolderRedirectionHealth
Contacts                         : Win32_FolderRedirectionHealth
Desktop                          : Win32_FolderRedirectionHealth
Documents                        : Win32_FolderRedirectionHealth
Downloads                        : Win32_FolderRedirectionHealth
Favorites                        : Win32_FolderRedirectionHealth
HealthStatus                     : 3
LastAttemptedProfileDownloadTime : 
LastAttemptedProfileUploadTime   : 
LastBackgroundRegistryUploadTime : 
LastDownloadTime                 : 
LastUploadTime                   : 
LastUseTime                      : 3/4/2020 8:53:56 AM
Links                            : Win32_FolderRedirectionHealth
Loaded                           : True
LocalPath                        : C:\WINDOWS\system32\config\systemprofile
Music                            : Win32_FolderRedirectionHealth
Pictures                         : Win32_FolderRedirectionHealth
RefCount                         : 1
RoamingConfigured                : False
RoamingPath                      : 
RoamingPreference                : 
SavedGames                       : Win32_FolderRedirectionHealth
Searches                         : Win32_FolderRedirectionHealth
SID                              : S-1-5-18
Special                          : True
StartMenu                        : Win32_FolderRedirectionHealth
Status                           : 0
Videos                           : Win32_FolderRedirectionHealth

Next, cleanup the output to see what are relevant filters can be used:

PS C:\Users\rasim> Get-CimInstance -ClassName Win32_UserProfile | Select LocalPath, Special, Loaded, RoamingConfigured

LocalPath                                 Special Loaded RoamingConfigured
---------                                 ------- ------ -----------------
C:\Users\rasim                              False   True             False
C:\WINDOWS\ServiceProfiles\NetworkService    True   True             False
C:\WINDOWS\ServiceProfiles\LocalService      True   True             False
C:\WINDOWS\system32\config\systemprofile     True   True             False

The output shows the Special or system profiles. Next, you probably should not be deleting profiles that are loaded, being utilized currently. Lastly, you specified it has to be local path, so you want to ensure that it is not a Roaming profile:

PS C:\Users\rasim> Get-CimInstance -ClassName Win32_UserProfile -Filter "Special <> 'True' and RoamingConfigured = 'False' and LocalPath LIKE '%sim%'" | 
Select @{Name='Profile';Expression={($_.LocalPath -split '\\')[-1] }}, LocalPath

Profile LocalPath     
------- ---------     
rasim   C:\Users\rasim

As mentioned above, I would also filter Loaded (e.g. “and Loaded = ‘False’”), but I am using the profile. As you can see everything is filtered and now we can use a calculated expression to just get the profile name. The [-1] represents the UpperBound value, the highest part of the array. To answer your last question,

$profiles = @()
$profiles += Get-CimInstance -ClassName Win32_UserProfile -Filter "Special <> 'True' and RoamingConfigured = 'False' and LocalPath LIKE '%sim%'" | 
            Select-Object -Property @{Name='Profile';Expression={($_.LocalPath -split '\\')[-1] }}, LocalPath

$profiles += [pscustomobject]@{Profile='All';LocalPath='All'}

$profiles = $profiles | foreach {$i=0} {$_ | Add-Member Index ($i++) -PassThru}

foreach ($profile in $profiles) {
    Write-Host -ForegroundColor Green ('{0}) {1}' -f $profile.Index, $profile.Profile)
}

Found the index stuff here, but looks similar to how you were referencing the item to delete in your above post: