我编写了一个非常基本的脚本来轮询机器以获取某些信息。除非单台机器的结果有多个条目,否则它可以完美地工作。例如,我正在扫描显示器连接,所有内容都可以导出到 Excel,除非被扫描的 PC 连接了多个显示器。更具体地说,一台连接了一个 DP 的 PC 给我“10”就好了。当一台 PC 有 2 个 DP 显示器时,在 PS 中,我得到:
"10"
"10"
但是 excel 给了我
System.Object[]
。
那么,我如何获得多行结果,两者都以适当的回车方式降落在同一个单元格中,或者如何让它们每个都有自己的单元格,但只输出一次机器名称?
这是我正在使用的脚本,我绝对是一个 PS 新手,所以请记住这一点,同时想知道为什么我可能会做一些愚蠢的事情。
Get-Content C:\temp\hostnames.txt | ForEach {
$details = Invoke-command -ComputerName $_ -ScriptBlock { Get-WmiObject WmiMonitorconnectionparams -Namespace root\wmi | ForEach-Object VideoOutputTechnology -ErrorAction SilentlyContinue }
if ( $details ) {
$props = @{
ComputerName = $_
DisplayType = $details
}
New-Object PsObject -Property $props
}
Else {
$props = @{
ComputerName = $_
DisplayType = 'Unavailable'
}
New-Object PsObject -Property $props
}
} | Sort ComputerName | Export-Csv C:\temp\Monitor_Report.csv -NoTypeInformation
预先感谢您的任何见解。
Export-Csv
及其内存中对应项 ConvertTo-Csv
,没有意义地支持具有包含 集合 属性的对象,例如数组。
如果你愿意 表示单个 CSV 列值中的所有集合元素,您必须自己创建集合的字符串表示形式,在您的情况下,这意味着将(潜在)
$details
数组的元素与 "`n"
(LF 换行符)连接起来) 或 "`r`n"
(CRLF 换行符),使用 -join
,字符串连接运算符。
这是一个简化的示例(使用
ConvertTo-Csv
立即打印结果):
$details = '10', '10' # sample input array
# Use -join "`n"` to create multiline string from the array,
# with each (stringified) element on its ow line.
[pscustomobject] @{ DisplayType = $details -join "`n" } |
ConvertTo-Csv
输出:
"DisplayType"
"10
10"
请注意,由于 "..."
中的封闭,多行值如何表示为
单列值。
[pscustomobject]
literal - [pscustomobject] @{ ... }
- 这是在 PowerShell v3+ 中创建 [pscustomobject]
(又名 [psobject]
)实例的首选(更简洁和高效)方法。