存在长字符串时,输出格式会截断属性

Output formatting is truncating properties when long strings are present

我有这个脚本,它接受两个对象并比较每个 属性 和 note属性,在这种情况下,我试图比较 Get-ADUser:[= 返回的两个 ADUser 对象16=]

Function Compare-ObjectProperties {
    Param(
        [PSObject]$ReferenceObject,
        [PSObject]$DifferenceObject 
    )


    $objprops = $ReferenceObject | Get-Member -MemberType Property,NoteProperty | % Name
    $objprops += $DifferenceObject | Get-Member -MemberType Property,NoteProperty | % Name
    $objprops = $objprops | Sort | Select -Unique
    $diffs = @()
    foreach ($objprop in $objprops) {
        $diff = Compare-Object $ReferenceObject $DifferenceObject -Property $objprop
        if ($diff) {            
            $diffprops = @{
                PropertyName=$objprop
                RefValue=($diff | ? {$_.SideIndicator -eq '<='} | % $($objprop))
                DiffValue=($diff | ? {$_.SideIndicator -eq '=>'} | % $($objprop))
            }
            $diffs += New-Object PSObject -Property $diffprops
        }        
    }
    if ($diffs) {$diffs | select propertyname,refvalue,diffvalue}
}

$ad1 = Get-ADUser user1 -Properties *
$ad2 = Get-ADUser user2 -Properties *
Compare-ObjectProperties $ad1 $ad2 | select propertyname,refvalue,diffvalue

结果只有两个字段:属性name 和 refvalue。第三个字段似乎不适合屏幕。 Format-Table -AutoSize 根本不会改变结果(我还尝试了 wrap、length 和 autosize 选项)。

事实上,即使我使用 Out-File result.txt 结果也只包括这两列。我认为脚本中的命令之一使用的格式覆盖了 format-table 和我的其他尝试,但我不确定是哪一个或如何查看。

如果我比较具有较短属性的对象,脚本工作正常。我什至可以只使用 get-aduser user1(不使用 -properties *),因为结果更加紧凑 returns 所有三个字段。

您已经知道屏幕上放不下太多内容。 Format-Table -auto 无法让它适应并且 Out-File 在幕后使用相同的 cmdlet 来处理该数据。将对象传递给 Out-File 将强制 PowerShell 将对象呈现为字符串,而这在这方面已经遇到了麻烦。来自 docs.microsoft.com

The Format-Table command assumes that the nearer a property is to the beginning of the property list, the more important it is. So it attempts to display the properties nearest the beginning completely. If the Format-Table command cannot display all the properties, it will remove some columns from the display and provide a warning.

不确定为什么没有看到警告。我也没有得到,我的 $WarningPreference 不应该阻止它。

通常这种情况发生在有许多属性要显示并且 PowerShell 使用 Format-List 时。我认为该阈值是 4,但我不记得了。由于您有 3 个属性没有发挥作用。

所以你可以根据场景做两件事

控制台输出

管道到 Format-List

在文件中输出

使用专为对象设计的输出格式。 Export-Csv 是显而易见的选择


旁注

真的比较这些用户对象的所有属性吗?我知道 -Properties * 使用简单,但它是一个性能猪,因为它查询非索引属性。如果可以,请将您的选择集减少到您实际需要的那些。