Powershell格式表错误

use*_*516 17 powershell

我试图运行以下代码来检索计算机上的本地用户列表.

gwmi win32_useraccount -Computername $env:computername -Filter "Domain='$env:computername'" |
  Format-Table Name,Description
Run Code Online (Sandbox Code Playgroud)

在PS1文件中运行时出现此错误:

 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 "f ormat-table" command which is conflicting with the
 default formatting.
     + CategoryInfo          : InvalidData: (:) [out-lineoutput],
 InvalidOperationException
     + FullyQualifiedErrorId :
 ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand

我理解这个问题的出现是因为管道的解析方式,但我无法弄清楚如何绕过它.

Ric*_*ard 21

Format-*cmdlet的没有做最终的输出,但是改变他们的投入格式化对象的序列.这些格式化对象Out-可能会被其中一个cmdlet 转换为实际输出Out-Default.

如果脚本具有多个不同的格式化对象集,则脚本中所有表达式的合并对象的最终输出Out-Default无法解决不一致问题.

修复:Out-Sting在每个输出生成管道的末尾添加一个以一次执行格式化一个表达式:

gwmi win32_useraccount -Computername $env:computername -Filter "Domain='$env:computername'" |
  Format-Table Name,Description | Out-String
Run Code Online (Sandbox Code Playgroud)