Trouble adding test to output (enabled system administrators)

38 views Asked by At

I'm having trouble with adding "=>" to each line of the output of the list of enabled administrators

$isEnabled = (Get-LocalUser | Where-Object {$_.Enabled}).Name
$localAdminUsers = (Get-CimInstance Win32_GroupUser | where {$_.GroupComponent -like "*admini*"} | select -ExpandProperty PartComponent).Name
$EnabledLocalAdmin = ($localAdminUsers | Where {$isEnabled -Contains $_}) #-join "`r`n"
for ($i=0; $i -lt $EnabledLocalAdmin.Count; $i++) { $EnabledLocalAdmins[$i] = "`n`t  => " + $EnabledLocalAdmin }
$EnabledLocalAdmins

Output from the above script:

=> Admin1 Admin2 admin3

The desired output should be:

=> Admin1
=> Admin2
=> Admin3
1

There are 1 answers

0
mklement0 On BEST ANSWER

$EnabledLocalAdmin is an array (contains multiple user names), so your output is to be expected, because when an array is stringified, its (stringified) elements are space-concatenated.[1]

A simple example:

$arr = 'foo', 'bar', 'baz'
"=> " + $arr  # -> '=> foo bar baz'

I suggest streamlining your code as follows, which also solves the problem:

# Get the usernames of all enabled local administrators.
$enabledLocalAdmins = 
  (
    Get-CimInstance Win32_GroupUser | 
    Where-Object GroupComponent -like *admini*
  ).PartComponent.Name |
  Where-Object { (Get-LocalUser $_).Enabled } 

# Display output.
$enabledLocalAdmins | ForEach-Object { "`n`t  => " + $_ }

[1] Technically, you can override this default separator via the $OFS preference variable, but that is rarely done in practice.