Monday, September 27, 2021

PowerShell Script to Add new Column to exisiting CSV file

 PowerShell Script to Add new Column to exisiting CSV file


$vmlists = Import-Csv 'D:\temp\file.csv'

$counter =  $vmlists.count

foreach($vm in $vmlists)

{

    $vmName=$vm.Name

    $NewColumnValue = Read-Host "Enter the DatastoreName for $vmName"

    $vm | Add-Member -NotePropertyName Datastore -NotePropertyValue $NewColumnValue

    $counter = $counter -1

    Write-Host $counter

}

$vmlists | Export-Csv 'D:\temp\file.csv' -NoTypeInformation



Exsisting CSV File:

"Name","PowerState","IP Address","NetworkName","Cluster","VMHost"

"vm1","PoweredOn","192.168.1.6","vlan1","cluster1","host01"

"vm2","PoweredOn","192.168.1.7","vlan2","cluster1","host02"


OutPut CSV File

"Name","PowerState","IP Address","NetworkName","Cluster","VMHost","Datastore"

"vm1","PoweredOn","192.168.1.6","vlan1","cluster1","host01","datastore01"

"vm2","PoweredOn","192.168.1.7","vlan2","cluster1","host02","datastore01"