Strange format-list behavior in this PowerShell script

A function is supposed to return one or more Objects, not formatted output data (which is intended for the host/screen).

In other words, don't use Format-* cmdlets inside a function

Simply remove |fl * from the last statement, and pipe the output of the test function call to Format-List instead:

function test {
    @("Administrator","SomeUser","SomeOtherUser") |% {
        $uname = $_;
        $u = gwmi win32_useraccount |? { $_.Name –eq $uname }
        if (-not $u) {
            write-host ("[-] "+ $uname + " does not exist!")
        } else {
            write-host ("[+] "+ $uname + ":")
            $u
        }
    }

    @("Administrator","SomeUser","SomeOtherUser") |% {
        $uname = $_;
        gwmi win32_groupuser -computer . | select GroupComponent,PartComponent |? { $_.PartComponent -match ",Name=`""+$uname+"`""}
    }
}

test |fl *

Along the same lines, at least for writing reuseable functions:

  • Don't use Write-Host in your functions - it's bad
  • Use full cmdlet names instead of aliases (like %, select, gwmi)

You might also benefit from using the -Query parameter with Get-WmiObject, and have WMI do the filtering instead of returning all users to powershell and then filtering them

Get-WmiObject -Query "SELECT * FROM Win32_UserAccount WHERE Name = '$uname'"