Creating profile array with powershell

473 views Asked by At

I'm still learning the basics of powershell, but I have come across an issue I can't seem to resolve as I just don't have enough knowledge.

I'm creating a script to do user profile migrations and I want the code to gather profiles from the local machine, convert the SID back to usernames and list them in a drop down box (which works), but only lists one user. I have this:

$Profiles = gwmi -Class Win32_UserProfile -Filter ("Special = False")
$output = foreach ($Profile in $Profiles)
{
try
{
$objSID = New-Object System.Security.Principal.SecurityIdentifier($profile.sid)
$objuser = $objsid.Translate([System.Security.Principal.NTAccount])
$objusername = $objuser.value
}
catch
{
$objusername = $profile.sid
}
Write-Host $objuser.value
$array = @($objuser)

Any ideas?

TIA!

2

There are 2 answers

2
alroc On BEST ANSWER

It appears that you're overwriting the contents of $array on each iteration of your foreach loop. Instead, append to it.

foreach ($Profile in $Profiles)
{
try
{
$objSID = New-Object System.Security.Principal.SecurityIdentifier($profile.sid)
$objuser = $objsid.Translate([System.Security.Principal.NTAccount])
$objusername = $objuser.value
}
catch
{
$objusername = $profile.sid
}
Write-Host $objuser.value
$array += @($objuser)
}

But I may be wrong. You've pasted only part of your script here (the braces for foreach aren't balanced, and we have no insight into how that drop-down list is being populated), so there may be something later on that's messing you up.

1
Frode F. On

See comments in code.

$Profiles = gwmi -Class Win32_UserProfile -Filter ("Special = False")
#You never output anything in your foreach-loop, so $output will be empty.. Removed Write-Host later in code to fix this
$output = foreach ($Profile in $Profiles) {
    try
    {
        $objSID = New-Object System.Security.Principal.SecurityIdentifier($profile.sid)
        $objuser = $objsid.Translate([System.Security.Principal.NTAccount])
        $objusername = $objuser.value
    }
    catch
    {
        $objusername = $profile.sid
    }

    #You've already saved "objuser.value to a variable... use it.. :) Also, You're catching returned objects with $output = foreach, so I'd suggest outputing the usernames and not just write them to the console. Replace `Write-Host $objuser.value` with `$objusername`
    $objusername

#You never closed your foreachloop. Added }
}

#Output collected usernames
$output

#This will always overwrite $array with a new array containing one user, objuser, only. Removed
#$array = @($objuser)