VMware Cloud Community
Sugar_
Contributor
Contributor
Jump to solution

ForEach loop not writing to export

$vms = Get-VM
$result = {}
#$export = "C:\scripts\HDD.csv"

ForEach ($vm in $vms) # loop through VM's in the vms variable array above
{

write-host $vm.name
$ok = get-vm $vm | get-harddisk | select -ExpandProperty filename
write-host $ok | Export-Csv C:\scripts\HDD.csv

}

 

Above script works as intended, returning the datastore path to each VM, but I cannot figure out how to export the results. The .csv was created but nothing wrote to it, either with the above script or one of the other ways I tried it. You can see I commented out the variable with the export path, I've also tried places the export-csv command outside of the loop and inside but prior to the final write-host $ok line.

 

Long time lurker, first time poster, and still figuring out PS and powerCLI. Thank you kindly.

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

You could also do

Get-VM -PipelineVariable vm | Get-HardDisk |
Select @{N='VM';E={$vm.Name}}, FileName |
Export-Csv C:\scripts\HDD.csv -NoTypeInformation -UseCulture


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

View solution in original post

4 Replies
LucD
Leadership
Leadership
Jump to solution

You could also do

Get-VM -PipelineVariable vm | Get-HardDisk |
Select @{N='VM';E={$vm.Name}}, FileName |
Export-Csv C:\scripts\HDD.csv -NoTypeInformation -UseCulture


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

Sugar_
Contributor
Contributor
Jump to solution

Thank you, that returned exactly what I wanted. Any chance you'd be able to tell me why my script didn't have the same results?

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Sure there are a couple of things 😆

Your Export-Csv was inside the foreach loop, meaning it would be overwritten by each iteration.
The Write-Host is for sending messages to the console, it doesn't place anything in the pipeline.
A foreach loop doesn't place anything in the pipeline, so even having the Export-Csv after the foreach block wouldn't have helped.
A Foreach-Object does place data in the pipeline.

But what you were trying to do could be done by just using the pipeline to pass objects from one cmdlet to the next.
And at the end of the pipeline everything in the pipeline is written to the CSV


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

0 Kudos
LucD
Leadership
Leadership
Jump to solution

What are you talking about?
Mind to expand on that statement?


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

0 Kudos