【发布时间】:2021-04-02 16:11:20
【问题描述】:
我正在尝试将列表导出到 CSV 文件。输出应该如下所示:
| Computer Name | BIOS | Operating System | Version | Disk Number | Size (GB) | Partition Type |
|---|---|---|---|---|---|---|
| DEVICE1 | UEFI | Microsoft Windows 10 Pro | 10.0.19042.0 | 0 | 954 | GPT |
| DEVICE1 | UEFI | Microsoft Windows 10 Pro | 10.0.19042.0 | 1 | 119 | GPT |
| etc... |
但是,CSV 文件中的输出如下所示:
| Count | Length | LongLength | Rank | SyncRoot | IsReadOnly | IsFixedSize | IsSynchronized |
|---|---|---|---|---|---|---|---|
| 2 | 2 | 2 | 1 | System.Object[] | FALSE | TRUE | FALSE |
相关代码
$Result = New-Object System.Collections.Generic.List[System.Object]
#Irrelevant Code...
foreach($Device in $Devices){
#More irrelevant code...
Write-Host "`tCompiling device information... " -NoNewline
try{
$Cmd = Invoke-Command -Session $Session -ScriptBlock{
Get-Disk | Foreach-Object{
[PSCustomObject]@{
"Computer Name" = $env:COMPUTERNAME
"BIOS" = if (Test-Path HKLM:\System\CurrentControlSet\control\SecureBoot\State) {"UEFI"} else {"Legacy"}
"Operating System" = Get-WmiObject -Class Win32_OperatingSystem | Select-Object -ExpandProperty Caption
"Version" = [Environment]::OSVersion | Select-Object -ExpandProperty Version
"Disk Number" = $_.number
"Size (GB)" = [int]($_.size/1GB)
"Partition Type" = $_.PartitionStyle
}
}
}
$Cmd = $Cmd | Select * -ExcludeProperty PSComputerName, RunspaceId
$Result.Add($Cmd)
Write-Host "Success" -ForegroundColor Green
}catch{
Write-Host "Failed" -ForegroundColor Red
$Result.Add(
[PSCustomObject]@{
"Computer Name" = $Device
"BIOS" = $QueryErrorMsg
"Operating System" = $QueryErrorMsg
"Version" = $QueryErrorMsg
"Disk Number" = $QueryErrorMsg
"Size (GB)" = $QueryErrorMsg
"Partition Type" = $QueryErrorMsg
}
)
Continue
}finally{
Remove-PSSession $Session
Write-Host "`tConnection terminated."
}
$Count++
}
if($DisplayResults){
$Result | ft -a
}
if($ExportToCsv){
$Result | Export-Csv -Path ($OutputDirectory + "\DiskPartitionAudit $((Get-Date).ToString('MM-dd-yyyy hh-mm-ss tt')).csv") -NoTypeInformation
}
有什么办法可以解决这个问题吗?谢谢!
【问题讨论】:
-
如果您已经定义了自己的 PSCustomObject 属性,为什么还要
$Cmd = $Cmd | Select * -ExcludeProperty PSComputerName, RunspaceId? -
如果我没有在其中包含它,而不是在导出或显示
$Result时,那么这些属性将包含在我的输出中。接受的答案为我解决了这个问题。 -
@iRon 因为 Invoke-Command 会为您添加这些内容。您知道,为了您的方便。我一直讨厌这样。即使是 -HideComputerName 你仍然可以得到一个 psscomputername 属性!
标签: powershell