Hi Guys,
Does anyone know how to easily append to a csv file?
I have a foreach loop that i want to retreive the vm name and mac address and then output to a csv file...
$outputcsv = "C:\output.csv"
foreach ($line in $cfg) {
$report = @(Import-Csv $outputcsv)
$var = Get-VM -Name $ServerName | select Name
$var2 = (Get-VM -name $ServerName | Get-NetworkAdapter | select MacAddress)
$report += $var + "," + $var2
$report | Export-Csv ($outputcsv) -noTypeInformation }
}
CSV too look like;
Name,MAC
test1,00-11-22-33-44-55
test2,11-22-33-44-55-66
test3,22-33-44-55-66-77
etc...
This is to then allow an insert into SCCM to enable a build.
Any ideas?
Many thanks,
Sean.
Sean, your basic idea is correct.
You import the CSV file, append new lines and export it again.
Before I can give you a solution, some questions, is the original CSV empty or pre-populated ?
Where does $ServerName come from ?
____________
Blog: LucD notes
Twitter: lucd22
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Hi Luc,
The $Servername is from another part of the script and is actually read in from a different csv file!
Basically, the script reads in a csv file with lots of info about how each server should be built (server name, os, memory, Hdd's etc...) then build the machines to spec and outputs a csv with Name & MAC such that it can then be imported into Microsoft SCCM to create the SCCM objects..
Perform the cloning
$taskTab[http://(New-VM -Name $ServerName -Template $SourceTemplate -VMHost (Get-VMHost -Name $desthost) -Datastore (Get-Datastore -Name $destdatastore) - RunAsync).Id|http://(New-VM -Name $ServerName -Template $SourceTemplate -VMHost (Get-VMHost -Name $desthost) -Datastore (Get-Datastore -Name $destdatastore) - RunAsync).Id] = $b[0]
sleep 5
Add System Drive to new Clone
$Global:memorytotal = $Memory * 1024
Get-VM -Name $ServerName | Set-VM -MemoryMB $Global:memorytotal -NumCpu $nocpus -Confirm:$false
$SystemdriveKB = $systemdrive * 1048576
Get-VM -Name $ServerName | New-HardDisk -CapacityKB $SystemdriveKB -Persistence persistent
The $servername bit changes in the foreach (the foreach i stuck in the example was just an example)
The original csv would be empty.
Cheers!!
Sean.
Try it with the following script
... $outputcsv = "C:\output.csv" if(Test-Path -Path "C:\output.csv"){ $report = @(Import-Csv $outputcsv) } else{ $report = @() } foreach ($line in $cfg) { Get-VM -Name $ServerName | %{ $vm = $_ $vm | Get-NetworkAdapter | %{ $row = "" | Select Name, MAC $row.Name = $vm.Name $row.MAC = $_.MacAddress $report += $row } } } $report | Export-Csv ($outputcsv) -noTypeInformation ...
The script can also handle guests that have more than 1 NIC.
____________
Blog: LucD notes
Twitter: lucd22
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Luc,
As always, you are a master!!! Worked perfectly 1st time!!!
Thanks so much,
Sean.