如何在powershell中向特定的csv列添加新数据

wn9m85ua  于 2022-12-04  发布在  Shell
关注(0)|答案(2)|浏览(297)

输入CSV如下:

预期的新CSV文件:

我正在从以下代码获取磁盘信息:

$Global:diskinfo=get-WmiObject win32_logicaldisk | select-object DeviceID, volumename, @{n="Size";e={[math]::Round($_.Size/1GB,2)}},@{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}

如何将此数据附加到原始csv。

b4lqfgs4

b4lqfgs41#

使用Import-Csv从输入csv导入数据,然后使用Export-Csv再次导出:

Import-Csv path\to\input.csv |ForEach-Object {
    $inputRecord = $_
    Get-WmiObject -ComputerName $inputRecord.ServerName -Class Win32_LogicalDisk |ForEach-Object {
        # Create 1 new object per row of output you want
        [pscustomobject]@{
            ServerName = $inputRecord.ServerName
            OS         = $inputRecord.OS
            Disk       = '{0}\' -f $_.DeviceID
            Size       = [math]::Round($_.Size/1GB,2)
            FreeSpace  = [math]::Round($_.FreeSpace/1GB,2)
        }
    }
} |Export-Csv path\to\output.csv -NoTypeInformation
q5lcpyga

q5lcpyga2#

请尝试以下操作:

$Global:diskinfo=get-WmiObject win32_logicaldisk | select-object DeviceID, volumename, @{n="Size";e={[math]::Round($_.Size/1GB,2)}},@{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}
    $ServerName = "Instance1"
    $OS = "Windows 10"
    foreach($row in $Global:diskinfo)
    {
       $row | Add-Member -NotePropertyName ServerName -NotePropertyValue $ServerName
       $row | Add-Member -NotePropertyName OS -NotePropertyValue $OS
    }

#change order of columns
    $Global:diskinfo = $Global:diskinfo |Select-Object -Property ServerName, OS, DeviceID, volumename, Size, FreeSpace
    $Global:diskinfo | Format-Table
    $Global:diskinfo | Export-CSV -Path C:\temp\test.csv

相关问题