Understanding Export-CSV
Hello world
I am writing (try it, I should say) to write a script that retrieves from vCenter all ESX hosts and for each host retrieves the guests (by selecting the name, powerstate, host, it feeds and memory) AND Gets the data store for each host) by selecting the name of DS, freespace and tot capacity).
I don't get the release scheduled in my CSV file I was hoping. Can someone tell me what I am doing wrong? I assumed that my data through the variable - $esxHost and so O which must pass the export.
Variable #Initialize
$Hosts = 0
$esxHost = 0
$Hosts = get-vmHost
{foreach ($esxHost in $Hosts)
Get - VM | Select name powerstate, host, memoryMB
Get-Datastore. Select name, freespacemb, capacitymb}
$esxHost | Export-Csv "C:\LUN_Report.csv" - noTypeInformation
JindiJee,
It should be able to do what you are looking for. Although this operation generates two CSVs because it's really two separate reports you're looking for.
Unless you try to print the data store for the virtual machine on the same line as the virtual machine, it would be a little different.
This script creates a hash table which is a nice way to push around then he in a CSV file.
You could cut this one place to make it more "One-liner", but it should help convey the image.
Let me know if you get this job or if it does not have what you think.
The first creates two hash tables and slapping in two CSVs. If you want to see your separate your VMS data warehouses.
The second script will add the data to the first hash store and list with the virtual machine. It is not configured to manage virtual machines with disks on more than 1 data store. This can be done with a few adjustments.
Guess I was bored... I added the 3rd which will add a line in your CSV for each data store associated with a virtual machine... This means that your VM can be included more than once, but it lists every DS.
This should give you a good idea on how you can play with the export to CSVs I like installation of hash table.
Tags: VMware
Similar Questions
-
Hello
I entered the following two functions in my shell powercli
Two functions I have installed function {Get-VMEvents
< #.
. Logbook
Get events for an entity or query all events.
. Description
This function returns the events for the entities. It is very similar to
cmdlet Get-vievent. Please note that get-VMEvent can handle 1 vm at a time.
You can't send picture of vms in this version of the script.
. Example of
Get-VMEvents 0All-types "VmCreatedEvent", "VmDeployedEvent", "VmClonedEvent".
He will receive all events of type "VmCreatedEvent", "VmDeployedEvent"
'VmClonedEvent '.
. Example of
Get-VMEvents-name 'vm1' - type 'VmCreatedEvent '.
Will be out of the events of creation of virtual machine: "vm1. It's faster than the vms piping is of
result of Get - vm. There is no need to use get - vm to move names to get-vmevents.
Yet, it is OK when you do, it will be just a little more slow < span class = "wp-smiley wp-emoji wp-emoji-blink of eye" title = ';') > ;) </span >
. Example of
Get-VMEvents-name 'vm1' - category 'WARNING '.
Will be out all events for vm: 'vm1. It is is faster than the names of piping of
cmdlet Get - vm. Category will get-vmevent to search only the defined category
events.
. Example of
Get - vm "vm1 | Get-VMEvents-types "VmCreatedEvent", "VmMacAssignedEvent".
Shows events for vm1 which will be regarding the events of creation,.
and events when when / what mac address is assigned
. VM parameter
This setting is a unique string that represents the name of the vm. He expects this single vm name
There in the virtual Center. Now in the first version of the script, it will only load a case
where there is 1 instance of vm selected name. In the future it will load multiple as
Well.
. Types of parameters
If none is specified, it will return all the events. If specified will return
Only the events with selected types. For example: "VmCreatedEvent."
"VmDeployedEvent", "VmMacAssignedEvent" "VmClonedEvent", etc...
. Category of a parameter
Possible categories are: warning, info, error. Please use this setting if you
you want to filter events.
. Setting all the
If you need to set this parameter, so command queries all events
Center Virtual Server virtual machines.
. Notes
NAME: VMEvents
AUTHOR: Grzegorz Kulikowski
LASTEDIT: 09/11/2012
DOES NOT? #powercli @ irc.freenode.net
. Link
# >
(param
[Parameter (ValueFromPipeline = $true)]
[ValidatenotNullOrEmpty()]
$VM,
[String []] $variétés.
[string] $category,
[switch] $All
)
$si = get-view ServiceInstance
$em is get-view $si. Content.EventManager
$EventFilterSpec = new-Object VMware.Vim.EventFilterSpec
$EventFilterSpec.Type = $types
{if ($Category)}
$EventFilterSpec.Category = $category
}
If {($VM)
$EventFilterSpec.Entity = new-Object VMware.Vim.EventFilterSpecByEntity
switch ($VM) {}
{$_-is [VMware.Vim.VirtualMachine]} {$VMmoref = $vm.moref}
{$_-is [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl]} {$VMmoref = $vm. ExtensionData.moref}
default {$vmmoref = (get - view - ViewType virtualmachine-filter @{'name' = $VM}) .moref}
}
$EventFilterSpec.Entity.Entity = $vmmoref
$em. QueryEvents ($EventFilterSpec)
}
If {($All)
$em. QueryEvents ($EventFilterSpec)
}
}
function get-vmcreationdate {}
< #.
. Logbook
Gets if possible virtual machine created.
. Description
This function will return the object with information about the creation time, method, of months,.
creator of particular virtual machine.
VMname: SomeVM12
Createduserid: 10/08/2012 11:48:18
CreatedMonth: August
CreationMethod: cloned
Creator: office\greg
This function displays NoEvent property in case when your VC do not
more information on these specific events, or your vm events no longer have
entries for the subject being created. If your VC data base has more tension date it is no longer possible
you find this event.
. Example of
Get-VMCreationdate - VMnames 'my_vm1', 'My_otherVM '.
This will return items that contain date information of creating virtual machines with names
myvm1 and myvm2
. Example of
Get-VM-location 'Cluster1 | Get-VMCreationdate
This will return items that contain information created for virtual machines that are
Located in Cluster1
. Example of
Notice-EEG - viewtype virtualmachine - SearchRoot (get-datacenter "mydc") user.user | Get-VMCreationDate
This will return items that contain information created for virtual machines that are
located in the data center "mydc" container If you use this feature in an existing loop where you
having the cmdlet get-view virtual machines, you can pass them via pipes or as a parameter VMnames.
. Example of
$report = get-cluster "cl-01' | Get-VMCreationdate
$report | Export-csv c:\myreport.csv
Stores all reported creationtimes object in the array $report variable and export the report to a csv file.
You can also filter the report before you write in the csv file using select
$report | Where-Object {$_.} {CreatedMonth - eq "October"} | Select VMName, CreatedMonth
So that you see only the vms that have been created in October.
. Example of
Get-vmcreationdate - VMnames "my_vm1", testvm55
WARNING: my_vm1 is not found, typo?
VMname: testvm55
Createduserid: 05/10/2012 14:24:03
CreatedMonth: October
CreationMethod: NewVM
Creator: home\greg
In case when you receive virtual machine that is not appropriate in the infrastructure of yor, a warning is displayed.
You can always store the full text of the report in the $report variable, but it includes all the information on
dates of creation of the missing vm. A warning always only for your information there is
probably a typing mistake in the name of the virtual machine.
. Parameter VMnames
This parameter must contain objects of virtual machine or strings representing vm
names. It is possible to supply this function wiith VM objects coming from get - vm or
get - view.
. Notes
NAME: Get-VMCreationdate
AUTHOR: Grzegorz Kulikowski
LASTEDIT: 27/11/2012
DOES NOT? #powercli @ irc.freenode.net
. Link
# >
(param
[Parameter (ValueFromPipeline = $true, mandatory = $true)]
[ValidateNotNullOrEmpty()]
[Object []] $VMnames
)
{in process
{foreach ($vm to $VMnames)
$ReportedVM = "" | Select VMname Createduserid, CreatedMonth, CreationMethod, creator
If ($CollectedEvent = $vm |) Get - VMEvents - types "VmBeingDeployedEvent", "VmRegisteredEvent", "VmClonedEvent", "VmBeingCreatedEvent" - ErrorAction SilentlyContinue)
{
If ($CollectedEvent.GetType ().) IsArray) {$CollectedEvent = $CollectedEvent |?} {{$_-is [vmware.vim.VmRegisteredEvent]}}
$CollectedEventType = $CollectedEvent.gettype () .name
$CollectedEventMonth = "{0: MMMM}" $CollectedEvent.CreatedTime f
$CollectedEventCreationDate = $CollectedEvent.CreatedTime
$CollectedEventCreator = $CollectedEvent.Username
Switch ($CollectedEventType)
{
"VmClonedEvent" {$CreationMethod = "Cloned"}
"VmRegisteredEvent" {$CreationMethod = "RegisteredFromVMX"}
"VmBeingDeployedEvent" {$CreationMethod = "VmFromTemplate"}
"VmBeingCreatedEvent" {$CreationMethod = "NewVM"}
default value {$CreationMethod = 'Error'}
}
$ReportedVM.VMname = $CollectedEvent.vm.Name
$ReportedVM.CreatedTime = $CollectedEventCreationDate
$ReportedVM.CreatedMonth = $CollectedEventMonth
$ReportedVM.CreationMethod = $CreationMethod
$ReportedVM.Creator = $CollectedEventCreator
} else {}
If ($?) {
If ($vm - is [VMware.Vim.VirtualMachine]) {$ReportedVM.VMname = $vm.name} else {$ReportedVM.VMname = $vm.} ToString()}
$ReportedVM.CreatedTime = 'NoEvent.
$ReportedVM.CreatedMonth = 'NoEvent.
$ReportedVM.CreationMethod = 'NoEvent.
$ReportedVM.Creator = 'NoEvent.
} else {}
$ReportedVM = $null
Write-Warning "$VM is not found, typo?
}
}
$ReportedVM
}
}
}
Now, if I use the first command
Get - vm testvm
I get a response of
Name PowerState Num CPU MemoryGB
---- ---------- -------- --------
Receiving TestVM 4 4,000
But if I do
Get-vmcreationdate testvm
he responds with
WARNING: testvm is not found. misspelling?
I can't understand why he says this?
What will be the final objective to query the server vcenter set and export a CSV of the creation of each day VM - is their an easier way to do it?
I was intending to use
get - vm | Get-VMCreationDate | Export-Csv-path "d:\\reports\vmcreationinventory.csv ".
But at the present time, each unique virtual machine is indicating "is not found."
Attached is an example with a virtual machine called gbvls
Although you may be better communicate with the author of these functions, from what I can tell, it seems to indicate that none of the specified events were found for these virtual machines.
You can check if there are targeted with the cmdlet Get-VIEvent ordinary events.
If you can see events, there could be a problem with the Get-VMEvents function.
$vmName = 'testvm '.
$tgtEvents = "VmBeingDeployedEvent", "VmRegisteredEvent", "VmClonedEvent", "VmBeingCreatedEvent".
$vm = get-VM-name $vmName
Get-VIEvent-body $vm - MaxSamples ([int]: MaxValue) |
Where {$tgtEvents - contains $_.} GetType(). Name}
-
Import of csv - Cluster Get - Export csv
Hello community vmware,
I'm looking for a script simple ps import a list of vm (based on a csv file that I feed into it).
I would then result to a csv file of the 2 column (1 column with the name of the virtual machine) and the other with the corresponding cluster name, in that it is.
Thanks in advance for the help.
Try something like this
It assumes that your input CSV file looks like this
Name
VM1
VM2
$report = import-Csv - UseCulture names.cvs | %{
Get-VM-name $_. Name |
Select Name,@{N='Cluster'; E = {Get-Cluster - VM $_______ |} Select name - ExpandProperty}}
}
$report | Export Csv report.csv - NoTypeInformation - UseCulture
-
UseCulture - Import/Export-Csv - switch. What is it?
Salvation;
I've seen a lot of references for the parameter - UseCulture importing content or exporters results of scripts to/from csv files. I tried in vain to find a real description or purpose of this function. Can anyone help direct me as to where I can find it or clarify on this setting?
Thank you. Ron
It forces the cmdlet Export-Csv to use the separator used in your locale to use.
By default there is a comma, but in other regions, it may for example be a semicolon.
-
Need help with an Export-CSV and ForEach loop
Hi guys, I'm total NOOB in CLI so please forgive the stupid question.
I need your expert advice for the very large environment and will award points.
I have a working script that alerts to our logout ESXi hosts, maintenance and NotResponidng mode
His job well, but need to send a mail to all three of our VCenters
Current script only works for a VC at a time. How do I ForEach and always the hose of the same body CSV and HTML
It would be nice to have an HTML and CSV output that looks like this (assuming that there are currently disconnected etc.)
I have a set of credentials, that work on all 3 of my VC
VC1
Host1 disconnected
Host2 NotResponding
VC2
Host3 disconnected
Host4 NotResponding
VC3
No disconnected/maintemance/notresponding hosts for VC3
Here is my current code, etc. of the hidden passwords >
# Clear old sessions
Disconnect VIServer VC01-confirm: $false# VC01 VC check for disconnection and Maintenance mode and does not
SE connect-VIServer-Server VC01 - FakeUSer username-password FakePassword$Report = get-VMhost-State disconnected, maintenance, NotResponding | SELECT name, connectionstate
# scan info to be html and give him a date stamp
$ReportHtml = $report | ConvertTo-Html | Out-string
# Write CSV file and give it a character of data
$filePath = "C:\PS\Output".
$filename = "VC01disconnectedHosts".
$CurrentDate = get-Date
$CurrentDate = $CurrentDate.ToString ('MM-dd-yyyy_hh-mm-ss')$Report | Export-Csv "C:\PS\Output\VC_$Currentdate.csv".
# Send the info by Mail
Send-MailMessage-to [email protected] - subject VMwareMorningcheckVC01$ CurrentDate '
SmtpServer - mail.sanlam.co.za - from [email protected] '
-BodyAsHtml-body $reportHtml - accessories 'C:\PS\Output\VC_$CurrentDate.csv '.Thank you in advance for help.
You could use a ForEach loop through all vCenters and combine the results in a $1 report.
Something like that
$vCenters = "VC01","VC02","VC03" # Clear old sessionsDisconnect-VIServer $vCenters -Confirm:$false $report = @()# Check VC VC01 for Disconnects and Maintenance mode and Not Respondingforeach($vc in $vCenters){ Connect-VIServer -Server $vc -User FakeUSer -Password FakePassword $Report += (Get-VMhost -State Disconnected,Maintenance,NotResponding | Select @{N="VC";E={$vc}},name ,connectionstate) Disconnect-VIServer $vc -Confirm:$false} # parse info to be html ,and give it date stamp $ReportHtml = ($report | ConvertTo-Html | out-String) # Write out CSV file and give it a Data Stamp $CurrentDate = Get-Date -Format 'MM-dd-yyyy_hh-mm-ss'$filename = "C:\PS\Output\DisconnectedHosts-$($CurrentDate).csv" $Report | Export-Csv -Path $filename -NoTypeInformation -UseCulture # Send info with Mail Send-MailMessage -To [email protected] -Subject VMwareMorningcheck$CurrentDate `-SmtpServer mail.sanlam.co.za -From [email protected] `-BodyAsHtml -Body $reportHtml -Attachments "C:\PS\Output\DisconnectedHosts-$($CurrentDate).csv"
I added the property vCenter for each line in the report
-
Export-Csv not generating expected results
I'm trying to generate a report from the script of grouping of NETWORK cards, but given the following code I will have to create Excel object and define its elements?The Export-Csv option does not work as I expect in this case. Thank you for your help. The following code:
($VMHost in Get-VMHost){
Foreach ($vSwitch in ($VMHost | Get-VirtualSwitch )){
$NicTeaming = Get NicTeamingPolicy -VirtualSwitch $vSwitch
$obj = new-object psobject
$obj | Add Member -membertype NoteProperty -name home -value $VMHost
$obj | Add Member -membertype NoteProperty -name vSwitch -value $vSwitch
$obj | Add Member -membertype NoteProperty -name NumPorts -value $vSwitch. NumPorts
$obj | Add Member -membertype NoteProperty -name NumPortsAvailable -value $vSwitch. NumPortsAvailable
$PG = $vSwitch | Get-VirtualPortGroup
If ($PG. Count-gt 1){
$obj | Add Member - membertype NoteProperty -nom échanges -valeur ([string] ::join()«, », ($PG)))
}
Else {}
$obj | Add-Member - membertype NoteProperty-trade name-value $PG
}
$obj | Add-Member - membertype NoteProperty - name BeaconInterval-$NicTeaming.BeaconInterval value
$obj | Add-Member - membertype NoteProperty - name LoadBalancingPolicy-$NicTeaming.LoadBalancingPolicy value
$obj | Add-Member - membertype NoteProperty - name NetworkFailoverDetectionPolicy-$NicTeaming.NetworkFailoverDetectionPolicy value
$obj | Add-Member - membertype NoteProperty - name NotifySwitches-$NicTeaming.NotifySwitches value
$obj | Add-Member - membertype NoteProperty - name FailbackEnabled-$NicTeaming.FailbackEnabled value
If ($NicTeaming.ActiveNic - gt 1) {}$obj | Add-Member - membertype NoteProperty-ActiveNic name-value ([string]: join (",", ($NicTeaming.ActiveNic)))
}
Else {}
$obj | Add-Member - membertype NoteProperty - name ActiveNic-$NicTeaming.ActiveNic value
}
If ($NicTeaming.StandbyNic - gt 1) {}
$obj | Add-Member - membertype NoteProperty-StandbyNic name-value ([string]: join (",", ($NicTeaming.StandbyNic)))
}
Else {}
$obj | Add-Member - membertype NoteProperty - name StandbyNic-$NicTeaming.StandbyNic value
}
If ($NicTeaming.UnusedNic - gt 1) {}
$obj | Add-Member - membertype NoteProperty-UnusedNic name-value ([string]: join (",", ($NicTeaming.UnusedNic)))
}
Else {}
$obj | Add-Member - membertype NoteProperty - name UnusedNic-$NicTeaming.UnusedNic value
}
$obj | Add-Member - membertype NoteProperty - name CheckBeacon-$NicTeaming.CheckBeacon value
$obj
$Report += $obj
}
$Report = $Report | Sort-Object VMName
IF ($Report - don't ' ")
{$Report |} {Export-Csv NIC - Teaming.csv}
}
You declare $report in a table?
On the first line
$report = @)
-
Is there a way to control or to format the output to a CSV of powercli? It seems that columns are always just in random order and I would be able to dictate that.
The problem is not with the Export-Csv cmdlet, but with the way in which the properties are stored in an object by PowerShell.
In PowerShell v2, you can explicitly specify the order before the Export-CSV
$array | Select prop1, prop1, prop2 | Export Csv C:\file.csv - NoTypeInformation - UseCulture
In PowerShell v3, you now have the casting [ordered].
See Export-Xlsx, the suite and the data ordered, who throw also works with Export-Csv
-
Include the attribute custom report (Export-Csv)
I am writing a script to report on disk / the use of the capacity for each virtual machine in the environment.
I try to include a column in the generated report (CSV), which includes the CustomField/CustomAttributes for each virtual computer as well as the news of disk capacity. The report runs fine, but after you export the report to CSV (Export-Csv using) the newly created column just to the custom attribute field displays the following parameters for each line/entry:
VMware.VimAutomation.ViCore.Impl.V1.Util.ReadOnlyDictionary'2 (System.String, System.String)
When I use out-file it works, but formatting is very obscured...
Here's the function/script that I use, I 'bolded in Red' the part of the script which I believe is the origin of the problem:
Function Get-VMGuestDiskUsage {}(param[parameter (valuefrompipeline = $true required = $true, HelpMessage = "enter an entity vm")]([VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl] $VM){in process$ErrorActionPreference = "SilentlyContinue".foreach ($disk in $VM. Guest.Disks) {}$objDisk = new-Object System.Object$objDisk | Add-Member - MemberType NoteProperty-VM name-value $VM. Name$objDisk | Add-Member - MemberType NoteProperty-name of Volume-value $disk. Path$objDisk | Add-Member - MemberType NoteProperty-CapacityMB name-value ([math]: round ($disk.) Capacity / 1 MB))$objDisk | Add-Member - MemberType NoteProperty-FreeSpaceMB name-value ([math]: round ($disk.) FreeSpace / 1 MB))$objDisk | Add-Member - MemberType NoteProperty - percent use of name-value ('{0:p2}' f (($disk.))) Capacity - $disk. FreeSpace) / $disk. Capacity))$objDisk | Add-Member - MemberType NoteProperty-name CustomFields-value ($VM. CustomFields)$objDisk}}}Get - VM * | Get-VMGuestDiskUsage | Export-Csv - NoTypeInformation c:\scripts\output\test.csv
Any help is greatly appreciated! Also please let me know if I did a poor job explaining the scenario and what I'm after here.
Hello, jSun311-
Because the property "CustomFields" itself is an object, and you try to get out of the strings to the CSV format, you must manage the object. You can replace the line in question by something like:
$objDisk | Add-Member -MemberType NoteProperty -Name CustomFields -Value (($VM.CustomFields | %{"$($_.Key) = $($_.Value)"}) -join ",")
Which would result in the output for the column that might look like:
dTestAttrib0 = someValue,dTestAttrib1 = AnotherValue
In other words, there is a list separated by characters of the key/value pairs in the CustomFields property for the virtual machine.
In addition, if you are interested, you might be able to clean up your code a bit by using the '-property ' New-Object parameter. As:
...foreach ($disk in $VM.Guest.disks) { New-Object PSObject -Property @{ VM = $VM.Name Volume = $disk.Path CapacityMB = [math]::Round($disk.Capacity / 1MB) FreeSpaceMB = [math]::Round($disk.FreeSpace/1MB) "Usage%" = "{0:p2}" -f (($disk.Capacity - $disk.FreeSpace) / $disk.Capacity) CustomFields = ($VM.CustomFields | %{"$($_.Key) = $($_.Value)"}) -join "," } ## end new-object} ## end foreach...
In this way, you shouldn't bother with calls Add-Member and repetitive cases here. Enjoy.
-
It is asked that we list all powered on virtual machines in a cluster to backup purposes. I am able to get this information into a CSV file. However, the backup engineer want a single file for each proxy server that uses this file to save these list of virtual machines.
A simple way to do this is the same as this:
# Author: Rhys Campbell# 2009-09-22# Split csv files# Path to the csv file. Must contain a sequential unique whole ID column$csvFile = "$Env:USERPROFILE\bigcsvFile.csv";# Slot in how many files?$split = 10;# Get the content of the csv file$content = import-Csv $csvFile.# If we start with Id = 1 in the csv file$start = 1;$end = 0;documents calc # per file$records_per_file = [ent] [Math]: ceiling ($content.) Count / $split);for ($i = 1; $i - $split; $i ++){# Set the value of end of selection of records$end += $records_per_file;# Need to cast to int or we get an alphabetical comparison when we want a digital$content | Where-Object {[int] $_.} ID - ge $start - and [int] $_. ID - the $end} | Export-Csv-Path "$Env:USERPROFILE\file$ i.csv '-NoTypeInformation;# Update the starting value for record selection$start = $end + 1;}Credit source: http://www.youdidwhatwithtsql.com/splitting-csv-files-with-powershell/374
I think that the next PowerCLI script will do the job.
param($Cluster, $NumberOfProxyServers = 3, $FileName = 'proxy') $VMs = Get-Cluster $Cluster | Get-VM | Sort-Object -Property Name $NumberOfVMs =$VMs.Count $NumberOfVMsPerProxyServer = $NumberOfVMs/$NumberOfProxyServers for($i = 0; $i -lt $NumberOfProxyServers; $i++) { $Range = (($i*$NumberOfVMsPerProxyServer)..(($i+1)*$NumberOfVMsPerProxyServer-1)) $VMs | Select-Object -Property Name | Select-Object -Index $Range | Export-Csv -Path "$FileName$i.csv" -NoTypeInformation -UseCulture }
Save the script as a .ps1 file, for example, New - VMProxyFile.ps1 and run it as:
. \New-VMProxyFile-cluster "YourClustername".
Proxy file numbers starting by 0. I hope this isn't a problem.
-
result of foreach not getting attached to the export-csv
Hello people,
I am trying to learn powercli. I use under commads to get information for VMs. looks like the results not add in the csv file. CSV file shows the result of the latest VM in import-csv file.
Q1 - can you please help identify what is bad in the commands below?
Q2 - How can I use a single export-csv command to get an output of lines both (get - vm and get-cluster)?
$vmname = import-csv "C:\vmname.csv".
{foreach ($_.name in $vmname)}
Get - vm $_.name | Select 'Name', 'Host ' | export-csv - UseCulture - NoTypeInformation C:\vmname-host-info.csv
Get-cluster - vm $_.name | Select 'name ' | export-csv - UseCulture - NoTypeInformation C:\vmcluster-info.csv}Thank you!
You're crushed the CSV file with each iteration of the loop.
Why do you want to produce 2 CSV files? Is it not easier to keep all the info in 1 file?
Her you could do something like that
$vmname = import-csv "C:\vmname.csv".
& {{foreach ($_.name in $vmname)}}
Get - vm $_.name | Select 'Name","Host",@{N="Cluster '; E = {Get-Cluster - VM $_______ |} Select name - ExpandProperty}}}} | Export-csv - UseCulture - NoTypeInformation C:\vm-info.csv
But the best is to use the track more PowerShell
$vmname = import-csv "C:\vmname.csv".
Get-VM-name $vmname |
Select Name,Host,@{N="Cluster; E = {Get-Cluster - VM $_______ |} Select name - ExpandProperty}} |
Export-csv - UseCulture - NoTypeInformation C:\vm-info.csv
-
Strange output from Get - VM... A cruise ship Export-CSV
If I type this in PowerCLI I get expected results
Get-Datacenter -name "name of my datacenter" | Get-VM | Where { ($_ | Get-CDDrive).ISOPath } | FT -auto Name, @{Label="OS"; Expression = { $_.Guest.OSFullName }}, @{Label="ISO file"; Expression = { ($_ | Get-CDDrive).ISOPath }}
But if I try to export to a CSV file
Get-Datacenter -name "name of my datacenter" | Get-VM | Where { ($_ | Get-CDDrive).ISOPath } | FT -auto Name, @{Label="OS"; Expression = { $_.Guest.OSFullName }}, @{Label="ISO file"; Expression = { ($_ | Get-CDDrive).ISOPath }} | Export-CSV virtual_machines_mounted_ISO.csv
I get output like this:
#TYPE Microsoft.PowerShell.Commands.Internal.Format.FormatStartData "ClassId2e4f51ef21dd47e99d3c952918aff9cd","pageHeaderEntry","pageFooterEntry","autosizeInfo","shapeInfo","groupingEntry" "033ecb2bc07a4d43b5ef94ed5a35d280",,,"Microsoft.PowerShell.Commands.Internal.Format.AutosizeInfo","Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo", "9e210fe47d09416682b841769c78b8a3",,,,, "27c87ef9bbda4f709f6b4002fa4af63c",,,,, "27c87ef9bbda4f709f6b4002fa4af63c",,,,, "27c87ef9bbda4f709f6b4002fa4af63c",,,,, "27c87ef9bbda4f709f6b4002fa4af63c",,,,, "27c87ef9bbda4f709f6b4002fa4af63c",,,,, "27c87ef9bbda4f709f6b4002fa4af63c",,,,, "27c87ef9bbda4f709f6b4002fa4af63c",,,,, "27c87ef9bbda4f709f6b4002fa4af63c",,,,,
What Miss me?
Try to replace the 'FT-auto' by 'Select-Object.
-
Export-csv system.string [] question
I have a powercli script I wrote to collect virtual switch information and portgroup.
Most work however the information active and reserve nic shows in the console
For example ActiveNic: {vmnic4}
However, in the CSV file it shows up as @{ActiveNic = System.String []} without the information real vmnic
Please let me know how to get the active and standby vmnic info in the CSV here is the script
SE connect-VIServer vcenter
$report = @)
$ESXhosts = Get-VMHost
{foreach ($esxhost to $ESXhosts)
$Vswitches = $esxhost | Get-Virtualswitch
{foreach ($vswitch to $vswitches)
$Portgroups = $vswitch | Get-VirtualPortGroup
{foreach ($portgroup to $Portgroups)
$nicteam = Get-NicTeamingPolicy $portgroup
$row = "" | Select Cluster, Vswitch, Portgroup, Vlan, ActiveNic, Esxhost, Standbynic
$row. Cluster = $esxhost. Parent
$row. ESxhost = $esxhost.name
$row. Vswitch = $Vswitch.Name
$row.portgroup = $portgroup.name
$row. VLAN is $portgroup. VLANID
$row. Activenic = $nicteam.activenic
$row. Standbynic = $nicteam. StandbyNic
{$report += $row}
}
}
$report | Export-Csv c:\psresults\host_portgroups_clustr_standby.csv
The Export-Csv cmdlet can manage properties that are arrays or complex objects correctly.
A way around this is to convert the table into a single string.
Something like that
Connect-VIServer vcenter $report = @() $ESXhosts = Get-VMHost foreach ($esxhost in $ESXhosts) { $Vswitches = $esxhost | Get-Virtualswitch foreach($vswitch in $vswitches){ $Portgroups = $vswitch | Get-VirtualPortGroup foreach ($portgroup in $Portgroups){ $nicteam = Get-NicTeamingPolicy $portgroup $row = "" | select Cluster, Esxhost, Vswitch, Portgroup,Vlan,ActiveNic,Standbynic $row.Cluster = $esxhost.Parent $row.ESxhost = $esxhost.name $row.Vswitch = $Vswitch.Name $row.portgroup = $portgroup.name $row.Vlan = $portgroup.Vlanid $row.Activenic= [string]::Join(',',$nicteam.activenic) $row.Standbynic=[string]::Join(',',$nicteam.StandbyNic) $report += $row} } } $report | Export-Csv c:\psresults\host_portgroups_clustr_standby.csv
-
Sorry for the newbie question (and thanks for any help) but I have a reporting need to enumerate WWPN of hosts per cluster.
With the below it will display csv as:
Name of host Hba WWPN
Server1 vmhba1 xxxxxx
Server1 vmhba2 xxxxxx
Server2 vmhba1 xxxxxx
Server2 vmhba2 xxxxxx
Is it possible to get to the exit of the csv like that? :
Hostname Hba1, Hba2 WWPN WWPN
Server1 vmhba1 xxxxx xxxxxx vmhba2
Server2 vmhba1 xxxxx xxxxxx vmhba2
or:
Hostname WWPN Hba1, Hba2-WWPN
Server1, vmhba2 vmhba1-xxxx-xxxxx
Server2, vmhba2 vmhba1-xxxx-xxxxx
I just need to be able to enumerate each server with its Hba and WWPN on its own line
I need to have it in this format in the turnover of another Department
{foreach ($vmh to $VMHs)
foreach ($hba in $vmh. ExtensionData.config.storagedevice.hostbusadapter) {}
If ($hba. PortWorldWideName) {}
$objWwpn = "" | Select Name of the host, Hba, WWPN
$objWwpn.HostName = $vmh. Name
$objWwpn.Hba = $hba. Device
$objWwpn.WWPN = '{0}': x f $hba. PortWorldWideName
$objHba += $ObjWwpn
}
}
}
$objHba | Export-csv .\"$ClusterName"_WWNs.csv E -NoTypeInformation
Try something like this
Import-Csv .\test.csv | Group-Object HostName | %{ $row = "" | Select Hostname,Hba1,WWPN1,Hba2,WWPN2 $row.Hostname = $_.Values[0] $row.Hba1 = $_.Group[0].Hba $row.WWPN1 = $_.Group[0].WWPN $row.Hba2 = $_.Group[1].Hba $row.WWPN2 = $_.Group[0].WWPN $row} | Export-Csv .\test2.csv -NoTypeInformation -UseCulture
-
$vms = Get-VM -rental "somehost"
foreach
($vm in $vms){
$vmobj_hds = $vm. Hard drives
foreach ($vmhd in $vmobj_hds){
Write-Host $vm. Name, $vmhd. File name}
}
I need to change that to Write-Host to Export-CSV with the following titles, the name of VM, HardDisk2 1 hard disk, etc. 1 hard disk should be the. HarDisk.Filename info. I've always had problems with the select - export-csv cmdlets and property. Any help would be appreciated.
Hello BrianGordon84-
Try something like:
## get the VMs, sort descending by number of harddisksGet-VM | Sort @{e={($_.ExtensionData.Config.Hardware.Device | ?{$_ -is [VMware.Vim.VirtualDisk]}).count}} -Descending | %{ $vm = $_ ## make an object in which to put the info $oInfo = New-Object -Type PSObject -Property @{VMname = $vm.Name} ## for each harddisk, add a property to the info object with the harddisk name and filename Get-HardDisk -VM $vm | %{ $oInfo | Add-Member -MemberType NoteProperty -Name $_.Name -Value $_.Filename } ## end foreach-object ## return the info object $oInfo} | Export-Csv -NoTypeInfo C:\temp\vmDiskInfo.csv
Sorting after the Get - VM is there to ensure that the first exported object has most of the hard drives, which is what makes the exported CSV have the right number of columns. The headers in the CSV file are made based on the first object out.
The code could be optimized a bit by using Get - view, but your question was about the Export-Csv.
How do I?
-
Hello!
I am trying to export-csv the following code, each obvious answer seems to fail or display the data too, can anyone help?
{foreach ($ClusterName Get-cluster)
foreach ($VMHost in Get-VMHost-location $ClusterName | where {$_.}) {Name - match "rxh *"} | {Name of sorting)
{{write-host $VMHost.Name, $ClusterName, $VMHost.CPUTotalMhz, $VMHost.MemoryTotalMB}}
Thank you
Steve
Try it like this
$report = @() foreach ($ClusterName in Get-Cluster) { foreach ($VMHost in (Get-VMHost -Location $ClusterName | where {$_.Name -match "rxh*"} | Sort Name)){ $row = "" | Select Name,ClusterName,CPUTotalMhz,MemoryTotalMB $row.Name = $VMHost.Name $row.ClusterName = $ClusterName.Name $row.CPUTotalMhz = $VMHost.CPUTotalMhz $row.MemoryTotalMB = $VMHost.MemoryTotalMB $report += $row } } $report | Export-Csv "C:\report.csv" -NoTypeInformation
You must remember that Write-Host sends the data to the console, while the Export-Csv cmdlet picks up what is in the pipeline (when used like this)
____________
Blog: LucD notes
Twitter: lucd22
Maybe you are looking for
-
A project now lets FCPX down.
Just a specific project. It started this morning. I tried all sorts of things without success. It is a 5-minute project that I invested at least 36 hours. How can I solve this problem?
-
"impressions" are empty! Help me please!
Whenever I try to rpint something, it comes out in white! Do I leterally JUST changed the cartridges - what is happening? I'm so cunfused.
-
You do not have a sound device installed on your computer error ID = 0xC00D11BA, Condition ID = 0x00000000
-
My front and rear camera are tranished... What can I do?
-
OfficeJet 6500 more Wireless connection.
I bought an OJ6500 more and tried to connect to my wireless network. My wireless access Point is a D-Link DWL-G700AP. I got this wireless network running for more than two years. We recently acquired an iPad and searched printers wireless in the comp