Deleting roaming profile

Hey folks,

I’m trying to delete some roaming profiles on machines that need to be cleaned up every few days.

I’m running the following code, but I get an error that I don’t know how to fix:

$Machine = "TestMachine" $User = "TestUser" Foreach ($Profile in (Get-WmiObject Win32_UserProfile -Computername $Machine | Where {$_.LocalPath -match "(c:\users\$user)(?![a-zA-Z0-9- _])"})) { try { $objSID = New-Object System.Security.Principal.SecurityIdentifier($Profile.SID) $CurUser = ($objSID.Translate([System.Security.Principal.NTAccount])).Value Write-Host "Deleting Profile for $CurUser" -ForegroundColor Yellow $Profile.Delete() Write-Host "$CurUser Profile Deleted" -ForegroundColor Green $TargetRoot = "\$Machinec`$Users" Foreach ($LPath in (Get-ChildItem $TargetRoot | Where {$_.Name -match "($user)(?![a-zA-Z0-9- _])" -and $user -notlike ""})) { takeown /f $LPath.FullName /r /d y | Out-Null Write-Host "Deleting $($LPath.FullName)" -ForegroundColor Yellow Remove-Item $LPath.FullName -Recurse -Force Write-Host "$($LPath.FullName) $(If(Test-Path $LPath.FullName){"NOT DELETED"}Else{"DELETED"})" -ForegroundColor Yellow} Write-Host "$CurUser profile and $($Profile.LocalPath) directory deleted successfully on $Machine" -ForegroundColor Green } catch { Write-Host "Error For $CurUser on $Machine - Error $($_.Exception.Message)" -ForegroundColor Red } } 

The output is:

Deleting Profile for TestDomainTestUser Error For TestDomainTestUser on TestMachine - Error Exception calling "Delete" with "0" argument(s): "" 

It looks like the Delete() function is asking for an argument?

If I run just this command I get a roaming profile (edited some details for security reasons):

PS C:windowssystem32> Get-WmiObject Win32_UserProfile -Computername $Machine | Where {$_.LocalPath -match "(c:\users\$user)(?![a-zA-Z0-9- _])"} __GENUS : 2 __CLASS : Win32_UserProfile __SUPERCLASS : __DYNASTY : Win32_UserProfile __RELPATH : Win32_UserProfile.SID="S-X-X-XX-XXXXXXXXXXX-XXXXXXXXXXX-XXXXXXXXXX-XXXXXX" __PROPERTY_COUNT : 12 __DERIVATION : {} __SERVER : TestMachine __NAMESPACE : rootcimv2 __PATH : \TestMachinerootcimv2:Win32_UserProfile.SID="S-X-X-XX-XXXXXXXXXXX-XXXXXXXXXXX-XXXXXXXXXX-XXXXXX" LastDownloadTime : 20190403102345.006000+000 LastUploadTime : 20190403110349.622000+000 LastUseTime : 20190814120831.029000+000 Loaded : True LocalPath : C:UsersTestUser RefCount : 0 RoamingConfigured : True RoamingPath : \TestDomainservicesProfilesTestUser.V2 RoamingPreference : True SID : S-X-X-XX-XXXXXXXXXXX-XXXXXXXXXXX-XXXXXXXXXX-XXXXXX Special : False Status : 2 PSComputerName : TestMachine 

Any help would be appreciated.


submitted by /u/solrackhamul
[link] [comments]

Leave a Reply