I have a weird behavior with format-list. When I paste the following code directly into the shell – everything works like a charm:
@("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+"`""} | fl *
}
However, when I put the same code in a function, say test, and call test, PowerShell drops an error about format-list. I cannot figure out why – maybe I have been searching on the wrong end, but I did not find anything.
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+"`""} | fl *
}
}
The error message displayed is:
out-lineoutput : The object of type "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" is not valid or not in the correct sequence. This is likely caused by
a user-specified "format-list" command which is conflicting with the default formatting.
+ CategoryInfo : InvalidData: (:) [out-lineoutput], InvalidOperationException
+ FullyQualifiedErrorId : ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand
A screenshot of the issue:
Best Answer
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 thetest
function call toFormat-List
instead:Along the same lines, at least for writing reuseable functions:
%
,select
,gwmi
)You might also benefit from using the
-Query
parameter withGet-WmiObject
, and have WMI do the filtering instead of returning all users to powershell and then filtering them