【问题标题】:powershell - displaying an array inside functionpowershell - 在函数内显示一个数组
【发布时间】:2020-06-29 21:08:57
【问题描述】:

所以我有一个对象

$appstatus=[pscustomobject] @{
 txtlist=@()
 csvlist=@()
 someotherproperties
}

以及加载 TXT 或导入 CSV 文件的函数。根据选择的文件名,它会填充 $appstatus 对象的一个​​属性。然后我有另一个函数来显示当前加载的列表。类似的东西

function showhosts(){
        if(($appstatus.txtlist).count -gt 0){
            write-host $appstatus.txtlist
        }else{
            write-host $appstatus.csvlist
        }
}

txtlist 很好,但问题出在 csvlist 上,因为 write-host 没有显示漂亮的表格格式,但是这个 @{property=value; ...} 长字符串。我不能在没有 write-host 的情况下只键入 $appstatus.csvlist,因为它不会被显示并成为函数的返回值,所以我怎样才能从函数中很好地显示对象,就像从函数中调用它一样主脚本?

【问题讨论】:

  • 你试过Format-Table吗?
  • | ft?将管道格式化为表格
  • 只要使用Out-Host --> $appstatus.txtlist | out-host
  • 添加到AdminOfThings' helpful answerWrite-Host 执行简单的.ToString() 字符串化(通常无用的单行表示),而Out-Host 使用PowerShell 丰富的显示格式系统。
  • @JonathonAnderson Write-Host 输出无法通过管道传输,因为它没有进入 PowerShell 的(成功)输出流,它(有效地)直接进入主机(显示)。请注意,OP 明确需要 not 写入输出流。

标签: powershell


【解决方案1】:

要求如下:

  1. 在控制台显示数据而不写入成功流。
  2. 显示默认的 PowerShell 格式输出

您可以为此目的使用Out-Host

function showhosts(){
        if(($appstatus.txtlist).count -gt 0){
            $appstatus.txtlist | Out-Host
        }else{
            $appstatus.csvlist | Out-Host
        }
}

Write-Host 默认不输出到成功流,打印到控制台时能力更强。从 PowerShell 5 开始,它会写入信息流,该信息流可以存储在变量中并在以后访问。如果您想通过典型的变量分配来捕获其输出,则信息流也可以重定向到成功流。但是,它确实将输出字符串化到控制台,这解释了@{property = value} 语法。然后在大多数系统上,任何[string] 强制转换数组都由一个空格连接,因为这是默认分隔符。

# Example 1
# Stringify simple array
Write-Host 1,2,3
1 2 3

# Example 2
# Stringify an array of custom objects
Write-Host $obj.two
@{property=value1} @{property=value2}

# Example 3
# Saving Write-Host output to variable $out using information stream
Write-Host $obj.two -InformationVariable out
@{property=value1} @{property=value2}
$out
@{property=value1} @{property=value2}

# Redirecting information stream to success stream
# Notice write-host no longer outputs to console after redirection
# $out has normal output plus write-host output
$out = "first line`n"
$out += Write-Host $obj.two 6>&1
$out
first line
@{property=value1} @{property=value2}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-01
    • 2020-09-29
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 2014-10-28
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多