VMware Cloud Community
nava_thulasi39

How to add export-csv in this simple script?

Hi,

Thanks for lot of scripts here.

Here is the script to collect vms list and cluster information. I have the list of vms as a excel file (csv file). So i tried like this

$vms = import-csv c:\scripts\vms.csv

foreach ($vmname in $vms)

{

get-vm $vmname.name | Select Name,@{N="cluster";E={Get-cluster -VM $_}}

} |

Export-Csv -NoTypeInformation -useculture C:\scripts\vminfo1.csv


In the excel sheet Name column for the VMs name.

But when i tried with export-csv here, I am getting the error

[vSphere PowerCLI] C:\scripts> .\Clusterdetailswithimport-csv.ps1

An empty pipe element is not allowed.

At C:\scripts\Clusterdetailswithimport-csv.ps1:6 char:3

+ }| <<<<

    + CategoryInfo          : ParserError: (:) [], ParseException

    + FullyQualifiedErrorId : EmptyPipeElement

Could someone help me, what's wrong adding export-csv here? Without export-csv the output is "OK"

If you find this or any other answer useful please consider awarding points by marking the answer correct or helpful
4 Replies
RvdNieuwendijk
Leadership
Leadership

You cannot use the output of the foreach statement in the pipeline because foreach is not a cmdlet. Try to wrap the foreach statement in &{}. Like:

&{ foreach {  ... } } | Export-CSV ...

Blog: https://rvdnieuwendijk.com/ | Twitter: @rvdnieuwendijk | Author of: https://www.packtpub.com/virtualization-and-cloud/learning-powercli-second-edition
0 Kudos
nava_thulasi39

Hi RvdNieuwendijk,

Thanks for quick answer.

Could you please help me how to insert &{ foreach {  ... } } | Export-CSV ? I am newbie in the scripting..

If you find this or any other answer useful please consider awarding points by marking the answer correct or helpful
0 Kudos
RvdNieuwendijk
Leadership
Leadership

Sure. What I meant was modifying your script into:

$vms = import-csv c:\scripts\vms.csv

& { foreach ($vmname in $vms)

{

get-vm $vmname.name | Select Name,@{N="cluster";E={Get-cluster -VM $_}}

}} |

Export-Csv -NoTypeInformation -useculture C:\scripts\vminfo1.csv

Blog: https://rvdnieuwendijk.com/ | Twitter: @rvdnieuwendijk | Author of: https://www.packtpub.com/virtualization-and-cloud/learning-powercli-second-edition
0 Kudos
LucD
Leadership
Leadership

You could do the same in a more PowerShell-like fashion as follows

Get-VM -Name (Import-Csv c:\scripts\vms.csv) |
Select Name,@{N="cluster";E={Get-cluster -VM $_}} |
Export-Csv -NoTypeInformation -useculture C:\scripts\vminfo1.csv

No need for the Foreach loop, use the PowerShell functionality to "loop" through all the objects that are placed on the pipeline.

The Name parameter on the Get-VM cmdlet accepts an array of names.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos