此 PowerShell 脚本中的奇怪格式列表行为

go *_*lla 3 powershell

我对格式列表有一个奇怪的行为。当我将以下代码直接粘贴到 shell 中时 - 一切都像魅力一样:

    @("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 *
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我将相同的代码放入一个函数中时,比如说 test 并调用 test,PowerShell 会抛出一个关于 format-list 的错误。我不知道为什么 - 也许我一直在寻找错误的一端,但我没有找到任何东西。

    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 *
        }
    }
Run Code Online (Sandbox Code Playgroud)

显示的错误消息是:

out-lineoutput :“Microsoft.PowerShell.Commands.Internal.Format.FormatStartData”类型的对象无效或顺序不正确。这可能是由
用户指定的“format-list”命令与默认格式冲突引起的。
+ CategoryInfo : InvalidData: (:) [out-lineoutput], InvalidOperationException
+ fullyQualifiedErrorId : ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand

问题截图:

在此处输入图片说明

Mat*_*sen 7

一个函数应该返回一个或多个对象,而不是格式化的输出数据(用于主机/屏幕)。

换句话说,不要在函数内使用 Format-* cmdlet

只需|fl *从最后一条语句中删除,并将函数调用的输出通过管道改为:testFormat-List

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 *
Run Code Online (Sandbox Code Playgroud)

同样,至少对于编写可重用的函数:

您还可以从使用-Query参数 with 中受益Get-WmiObject,并让 WMI 进行过滤,而不是将所有用户返回到 powershell然后过滤它们

Get-WmiObject -Query "SELECT * FROM Win32_UserAccount WHERE Name = '$uname'"
Run Code Online (Sandbox Code Playgroud)