代码:
$path = 'C:\Users\Desktop\Test.csv'
If (Test-Path $path)
{
Remove-Item $path -verbose
}
else { Write-Host "$path not found" }
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Storage.Vds") | Out-Null
$oVdsServiceLoader = New-Object Microsoft.Storage.Vds.ServiceLoader
$oVdsService = $oVdsServiceLoader.LoadService($null)
$oVdsService.WaitForServiceReady()
$oVdsService.Reenumerate()
$cDisks = ($oVdsService.Providers |% {$_.Packs}) |% {$_.Disks}
$cPacks = $oVdsService.Providers |% {$_.Packs}
foreach($oPack in $cPacks)
{
If($oPack.Status -eq "Online" -and $oPack.Volumes -ne $null)
{
foreach($oDisk in $oPack.Disks)
{
foreach($oVolume in $oPack.Volumes)
{
$data= new-object psobject -Property @{
'DiskGuid' = $oDisk.DiskGuid
'Name' = $oDisk.FriendlyName
}
}
}
$final = $data | ConvertTo-Csv -Delimiter "|" -NoTypeInformation
$final | Add-Content $path
}
}
}
以 CSV 文件输出
“姓名” | “磁盘向导” |
---|---|
“DELL PERC H740P 迷你 SCSI 磁盘设备” | “5b932319-8cb4-4909-96c0-f85db3671c91” |
“姓名” | “磁盘向导” |
“DELL PERC H740P 迷你 SCSI 磁盘设备” | “5b932319-8cb4-4909-96c0-f85db3671c91” |
“姓名” | “磁盘向导” |
“HITACHI OPEN-V 多路径磁盘设备” | “2f3563e7-66c9-4a8a-9bea-d3e856b839eb” |
“姓名” | “磁盘向导” |
“HITACHI OPEN-V 多路径磁盘设备” | “2f3563e7-66c9-4a8a-9bea-d3e856b839eb” |
CSV 中的预期输出:
“姓名” | “磁盘向导” |
---|---|
“DELL PERC H740P 迷你 SCSI 磁盘设备” | “5b932319-8cb4-4909-96c0-f85db3671c91” |
“DELL PERC H740P 迷你 SCSI 磁盘设备” | “5b932319-8cb4-4909-96c0-f85db3671c91” |
“HITACHI OPEN-V 多路径磁盘设备” | “2f3563e7-66c9-4a8a-9bea-d3e856b839eb” |
“HITACHI OPEN-V 多路径磁盘设备” | “2f3563e7-66c9-4a8a-9bea-d3e856b839eb” |
任何人都可以帮助如何获取预期输出中显示的值?
循环逻辑可以简化为:
$oVdsService.Providers |
Where-Object Status -EQ Online |
Where-Object { -not [string]::IsNullOrWhiteSpace($_.DriveLetter) } |
Select-Object DiskGuid, @{ N = 'Name'; E = { $_.FriendlyName } } |
Export-Csv $path -Delimiter '|' -NoTypeInformation
您的问题是为循环中的每个对象调用
ConvertTo-Csv
并将其附加到文件中。这导致每个附加对象都有一个标题和单行。您应该做的是将表达式的输出直接通过管道传输到 Export-Csv
。