user6730445
user6730445

Reputation:

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 '$DomainUser' 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.

Upvotes: 0

Views: 669

Answers (2)

Chris Dent
Chris Dent

Reputation: 4240

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])

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

... -match '$DomainUser' ...

PowerShell expands Variables only in double-quoted strings, not in single-quoted strings. Replace the single quotes with double qoutes or remove the quotes entirely.

Upvotes: 1

Related Questions