Get-UserProfile
Windows: Retrieves information about user profiles on a computer
#Requires -Version 5.1
[CmdletBinding()]
Param
(
[string]$ComputerName = $env:COMPUTERNAME,
[switch]$IncludeSpecial,
[pscredential]$Credential
)
Process
{
try
{
$cimParams = @{
'ClassName' = 'Win32_UserProfile'
'ErrorAction' = 'Stop'
}
if ($ComputerName -ne $env:COMPUTERNAME)
{
$sessionParams = @{
'ComputerName' = $ComputerName
}
if ($null -ne $Credential)
{
$sessionParams.Add('Credential', $Credential)
}
$cimParams.Add('CimSession', (New-CimSession @sessionParams))
}
$profiles = Get-CimInstance @cimParams
if (-not $IncludeSpecial)
{
$profiles = $profiles | Where-Object { $_.Special -eq $false }
}
$results = foreach ($p in $profiles)
{
$account = $null
try
{
# Attempt to resolve SID to a name using CIM (works for local and cached domain accounts)
$account = Get-CimInstance -ClassName Win32_UserAccount -Filter "SID = '$($p.SID)'" -ErrorAction SilentlyContinue
}
catch {}
[PSCustomObject]@{
ComputerName = $ComputerName
LocalPath = $p.LocalPath
LastUseTime = $p.LastUseTime
SID = $p.SID
UserName = if ($account) { "$($account.Domain)\$($account.Name)" } else { "Unknown" }
IsLoaded = $p.Loaded
}
}
Write-Output ($results | Sort-Object LastUseTime -Descending)
}
catch
{
throw
}
finally
{
if ($cimParams.ContainsKey('CimSession'))
{
Remove-CimSession $cimParams.CimSession
}
}
}Specifies the name of the computer to query. Defaults to the local computer.
Off
If set, includes system and special profiles (e.g., LocalSystem, NetworkService) in the list.
Specifies a PSCredential object for remote connection.