Home > OS >  How to add new data to specfic csv column in powershell
How to add new data to specfic csv column in powershell

Time:11-17

Input CSV as below:

enter image description here

Expected new CSV file :

enter image description here

I'm getting disk info from below code:

$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)}}

How I can append this data to original csv.

CodePudding user response:

Use Import-Csv to import the data from the input csv, then Export-Csv to export it again:

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

CodePudding user response:

Try following :

    $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
  • Related