Rich Maclannan Rich Maclannan - 2 months ago 6x
PowerShell Question

Searching using variable in Powershell

So I'm trying to find the SID for a user that's logged onto a system before. Our system has a split of non-administrative users (without a # at the start) and administrative users (with a #). My PowerShell script so far is this:

$CurrentDomainUser = wmic computersystem get username
$Separator = "\"
$CurrentDomainUserSplit = $CurrentDomainUser.split($Separator)
$DomainUser= $CurrentDomainUserSplit[3]

New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_Users

$UserSID = ls 'hklm:software/microsoft/windows nt/currentversion/profilelist' | ? {
$_.getvalue('profileimagepath') -match '$DomainUser' -and
$_.getvalue('profileimagepath') -notmatch '#'
} | % pschildname

This script doesn't work if I have use the
in the final
$UserSID = ...
line above. It does work if I put in the actual value that I'm searching for.

I'm guessing this is a simple PowerShell syntax problem.


Using Get-WmiObject instead of wmic

$DomainUser = (Get-WmiObject Win32_ComputerSystem).Username -replace '^.+\\'
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_Users
$UserSID = Get-ChildItem 'HKLM:/software/microsoft/windows nt/currentversion/profilelist' |
    Where-Object { $_.getvalue('profileimagepath') -match $DomainUser -and $_.getvalue('profileimagepath') -notmatch '#'} |
    ForEach-Object pschildname

Using NTAccount.Translate

Windows already knows how to translate names to security identifiers. We might use use this method of getting to a SID.

$userName = (Get-WmiObject Win32_ComputerSystem).Username 
$ntAccount = New-Object System.Security.Principal.NTAccount($userName)
$sid = $ntAccount.Translate([System.Security.Principal.SecurityIdentifier])