Help with trim output.

This topic contains 2 replies, has 3 voices, and was last updated by  js 3 weeks ago.

  • Author
    Posts
  • #84445

    Tobias Hallman
    Participant

    Hi,
    So im doing a script that will remove old userprofiles of a remote computer.
    i know this script is not working atm i have started to rebuild it from a previus version that only ran localy.

    Param(
    [Parameter(Position=0)]
    [ValidateNotNullorEmpty()]
    [int]$Days=10),
    
    [string]$Computer = Read-Host "what computer"
    
     
    
    Start-Transcript -Path \\***\c$\scriptlogs\ProfileCleanup.txt -Append
     
    Write-Warning "Filtering for user profiles older than $Days days" 
    $profil = Get-CimInstance win32_userprofile -Verbose | 
    Where {$_.LastUseTime -lt $(Get-Date).Date.AddDays(-$days)}
    
    $list = Get-CimInstance -ComputerName **** -Class win32_userprofile | select LocalPath
    
    $trim = $list.TrimStart("c:".TrimEnd("\"))
    
    write-host $trim
    
    read-host = $yes "Do you wanna remove all typ Y"
    
    if ($yes -eq "Y"){
    Remove-CimInstance -Verbose -ErrorAction Ignore 
    
    }
     
    Stop-Transcript
    

    Problem is that i get a few return values of diffrent lenght i wanna trim them down to only the username.

    OUTPUT
    C:\Users\defaultuser0
    C:\Users\username1
    C:\Users\username2
    C:\Users\username3
    C:\Users\admin account1
    and so on,
    i also get
    C:\windows\ServiceProfiles\NetworkService
    C:\windows\ServiceProfiles\LocalService
    C:\WINDOWS\system32\config\systemprofile

    output should look like

    username1
    username2
    admin account1

    mind that this will run on a client that might have alot more profiles.

    all help is welcome

    thank you so much in advance
    Tobias
    a powershell beginner.

  • #84460

    Simon Wåhlin
    Participant

    Hi,

    You could replace line 16 with something like this:

    $list = Get-CimInstance -Class win32_userprofile -Filter "Special='False'" | 
        Select-Object -ExpandProperty LocalPath | 
        Split-Path -Leaf
    
      Using -Filter "Special='False'" will remove all those "special" profiles like LocalService
      Using Select-Object with the parameter -ExpandProperty will return only the values of the property (instead of an object with that property)
      Using Split-Path -Leaf will give you only the name of the folder (which should be the username)

    Hope this will help!

  • #84560

    js
    Participant

    Btw there's a group policy to delete old profiles on restart. Also in windows 10, a lot of extra user or sid specific crap (app related) gets left around even though the profile is deleted. Rebooting seems to clean some of it.

You must be logged in to reply to this topic.