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 = @)

Tags: VMware

Similar Questions

  • Simple find() return is not the expected results

    I'm new to ColdFusion, but have been programming for a while now.  I have (what seems) an easy problem that I thought would be a simple solution, but I'm currently stuck.  Any guidance would be appreciated!

    I have the following code:

    < cfset brand = Trim (products. BRAND name) / >
    < cfif Find (brand name, ",") >
    < cfset brand = ""' & brand & ' "" / >

    < / cfif >

    My goal is to surround the text with 'if the string contains a comma.  I tried the standard comma, as Chr (44), but neither returned the expected results.

    What I am doing wrong?  The CSV file, creating, is sprayed upward for the name of a company is like 'Test Company, Inc.'

    Please help us save my sanity!  TIA!

    I think the first thing we do is to read the docs.  And if you may have read 'em a little closer... ;-)

    http://livedocs.Adobe.com/ColdFusion/8/htmldocs/functions_e-g_21.html#5177400

    How around two parameters go?

    --

    Adam

  • not displaying recordset is not the expected results

    Hello

    I try to get the recordset to display only users with an access level of 1 and the person that is connected only to assign the task to.

    $paramUser_rsTaskUsers = "-1";
    If (isset($_SESSION['kt_login_id'])) {}
    $paramUser_rsTaskUsers = (get_magic_quotes_gpc())? $_SESSION ['kt_login_id']: addslashes($_SESSION['kt_login_id']);
    }
    @mysql_select_db ($database_cbank, $cbank);
    $query_rsTaskUsers = sprintf ("" SELECT * FROM users WHERE AccessLevel = 1 AND UserID = %s ", GetSQLValueString ($paramUser_rsTaskUsers,"int")");
    $rsTaskUsers = mysql_query ($query_rsTaskUsers, $cbank) or die (mysql_error ());
    $row_rsTaskUsers = mysql_fetch_assoc ($rsTaskUsers);
    $totalRows_rsTaskUsers = mysql_num_rows ($rsTaskUsers);

    y at - it something wrong with my request as it is only showing to the user who is logged in the drop-down list to the bottom of the list and not the accesslevel = 1 users too.

    Thank you very much

    Your application uses AND, which means that both conditions must be met: 1 user access level and specific ID. As a result, you will get a single result.

    If you want all the people with the 1 and the specific user access level (regardless of the level of access), to modify AND where.

  • REGEXP_LIKE return is not the expected results

    My first attempt at REGEXP_LIKE and I am obviously missing something. I tried several suggestions I found on the forum but can not get the correct results. I need the following query to return only rows with only alphabetic characters (no numbers). What I get are lines containing letters and numbers.

    Any help will be greatly appreciated!

    Randy

    SELECT order_number
    Of order_table
    where REGEXP_LIKE (order_number, "[a - z A - Z]")
    select order_number
    from order_table
    where regexp_like(order_number,'^[[:alpha:]]+$')
    

    Published by: michaels2 on 10 Sep 2009 15:51

    No need to 'i '.

  • Invoke VMScript not return expected results

    Hello

    I use VMScript-Invoke to call a script, then return to the State of the output of the script. Since it is Linux I'm back the $? variable.

    To simplify the problem, I wrote a little script on my linux system which is as follows:

    #! / bin/bash
    Output 1

    I have this saved in / tmp and called it exit1.sh. If I run this command line, I get this back:

    (root@au-lab) / tmp$. / exit1.sh; ECHO $?

    1

    If I run VM script I get:

    Invoke-VMScript - VM AU-GSCLAB-7 - ScriptText "/ tmp/exit1.sh;» echo "" $? "- GuestPassword root password - GuestUser |" Select ScriptOutput - ExpandProperty

    0

    PowerCLI Version

    ----------------

    VMware vSphere PowerCLI 5.0.1 build 581491

    ---------------

    Versions of the snap

    ---------------

    VMware AutoDeploy PowerCLI component 5.0 build 544967

    VMware ImageBuilder PowerCLI component 5.0 build 544967

    License of VMware PowerCLI component 5.0 build 544881

    VMware vSphere PowerCLI component 5.0 build 581435

    Hello

    It looks like we have some problems with the redirection of output and the "echo". I log a bug for this. I don't know if this will help, but you can get the exit code of the script of the VMScriptResult returned by Invoke-VMScript:

    Invoke-VMScript - VM AU-GSCLAB-7 - ScriptText "/ tmp/exit1.sh ' GuestPassword - root password - GuestUser | Select ExitCode - ExpandProperty

    1

  • % ROWCOUNT SQL does not return the expected result

    I have the following function within a package:

    --Update APPERY_JTI_deleted_USERS table:
    FUNCTION fn_updt_app_jti_dlt_usr(
        p_update_co      IN VARCHAR2,
        p_appery_user_id IN APPERY_JTI_deleted_USERS.appery_user_id%TYPE,
        p_outlet_code    IN APPERY_JTI_deleted_USERS.outlet_code%TYPE)
      RETURN NUMBER
    AS
    lv_sql       VARCHAR2(4000);
    lv_rowcount  NUMBER := 0;
    BEGIN
    
    lv_sql := 'UPDATE APPERY_JTI_deleted_USERS SET '||p_update_co||' = 1 WHERE '||p_update_co||' = 0 AND OUTLET_CODE = '''||p_outlet_code||''' AND APPERY_USER_ID = '''||p_appery_user_id||'''';
    
    --EXECUTE IMMEDIATE lv_sql;
    EXECUTE IMMEDIATE 'BEGIN ' || lv_sql || '; :z := sql%rowcount; END; ' USING OUT lv_rowcount ;
    
    RETURN lv_rowcount;
      
    EXCEPTION
    WHEN OTHERS THEN
      RETURN -1;  
    END fn_updt_app_jti_dlt_usr;
    
    

    The function called several times as part of a job. Basically, the main function (Say M), call a few functions (for example A1... A9). Each of these functions is to do something and updated the application using the above function. Therefore, each of the nine functions will call the above function with different parameters.

    The problem that I am facing is:

    First run, invoke only first of all for the above function will return the positive result ($sql rowcount > 0). When I run M the second time, only first and second calls for the above function will be to return positive results and so on.

    How odd, it's that if I change the values again and run a function M, it will start from the beginning. And what strange more, the dynamic update statement is executed correctly and data are updated successfully. It's just sql rowcount % do not return is not the expected results.

    I tried to run execute immediately without (begin, end). I also tried to run it without HELP ON. It's always the same. I'm really confused, what Miss me here.

    I don't know if this is relevant. But for what it's worth, invoking the function above updates the SAME lines in the table appery_jti_deleted_users that the columns are different. So for all the work, the same lines need to be updated. Each function (A1... A9) will call the above function to update a different column of these lines.

    If you REALLY want to help you having US SHOW, not tell us:

    1. WHAT you do

    2. HOW to

    3. WHAT results you get

    4. WHAT results you expect to get

    First run, invoke only first of all for the above function will return the positive result ($sql rowcount > 0). When I run M the second time, only first and second calls for the above function will be to return positive results and so on.

    How odd, it's that if I change the values again and run a function M, it will start from the beginning. And what strange more, the dynamic update statement is executed correctly and data are updated successfully. It's just sql rowcount % do not return is not the expected results.

    Perhaps that the foregoing is true and maybe he's not. We have NO WAY of knowing because you don't SHOW US anything.

    I tried to run execute immediately without (begin, end). I also tried to run it without HELP ON. It's always the same.

    Yet once you showed us NOTHING >

    You do NOT FOLLOW best practices when you use dynamic sql statements: the sql statement real so that you can print:

    1 SEE what's running - make sure there are no syntax errors, and it seems to be what you wanted

    2 EXECUTE/TEST manually - to see if he really runs without error and see what results it really give.

    3. FIX any syntax or other problems and retest it

    Instrument properly your code and you won't have the problems you are having.

    You should know by now what are the parameters are transmitted when you run the function. So, there are at least three sets of these parameters.

    So you should be able to:

    1 run the instrumented manually function three times

    2. see that all three SQL statements are

    3 manually run these instructions

    4. see that the number of lines is after each execution

    We have no idea of what the output of the function is every time you call it. Apparently, you have, if you save the results of the function somewhere, but you didn't post any of this info.

    We need real details to help you - just listen to your story is not enough.

  • 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

  • Virtual MACHINE created on date export csv - get - vm testvm works but says testvm get-vmcreationdate is not found.

    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

    http://psvmware.WordPress.com

    # >

    (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

    http://psvmware.WordPress.com

    # >

    (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}

  • Export error records 'diagnosis package cannot be recovered from VMware vCenter Converter Standalone. "Error: could not generate file diagnosis of VMware vCenter Converter Standalone server.

    Hey, gentlemen!

    Trying to export logs from VMware vCenter Converter Standalone v 5.5.2 and this error occurs.

    "The package of diagnosis cannot be recovered from VMware vCenter Converter Standalone. "Error: could not generate file diagnosis of VMware vCenter Converter Standalone server.

    Can he save data to the file journal, but only coverter_gui newspapers, nothing else.

    Google search returns no results at all.

    What could be?

    OK, it is resolved after you restart the converter Services.

  • Export csv button call don't link not?

    GDay,

    I was wondering if it is possible to call the export csv via a button feature and functionality of default hyperlink?

    See you soon

    Hello

    You really need to mess with two models - the region one and a new button we.

    First of all, update model area of the report to include the following in the upper part of the setting "Template":

    <script type="text/javascript">
    var regionid="#REGION_ID#"
    </script>
    

    Note that this must be done on the model of the report, even if you put your button in another region because we need value REGION_ID report

    Now create a new model of button called, say, "Export" button The 'model' for this must be set:

    <a href="javascript:void(0)" class="t12Button" onclick="doExport();">Export</a>
    

    This was based on a standard model of button "button. If you use a different style of button, adjust accordingly - you need the same attributes href and onclick as shown above, but nothing else can be unchanged.

    Finally, the parameter header HTML of the page, add:

    <script type="text/javascript">
    function doExport()
    {
     var url = 'f?p=&APP_ID.:&APP_PAGE_ID.:&SESSION.:FLOW_EXCEL_OUTPUT_' + regionid + '_en';
     document.location.href=url;
    }
    </script>
    

    You can now change your button in a button-based model by using the new export button.

    Note that, as we are assigning to a javascript variable, 1 REGION_ID only this button can exist on a page.

    Andy

  • 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

  • Can not get the result of the command output to a text file...

    Hello

    I tried to get a list of my virtual machines (using PowerCLI) with CBT (block change tracking) enabled, and while the following command returns the results, I can't have it at the output to a text file. Any help you can offer would be appreciated.

    foreach ($vm in get - vm) {write-host $vm; get-advancedsetting - entity $vm | select-string - pattern 'ctkEnabled' | sort; write-host | out-file c:\somepath\file.txt}

    I get the correct result on screen, but the text file is empty.

    Please notify.

    Thank you

    Hello, wmilligan2013-

    You can get the information to an output file by removing the Write-Host calls.  How to do:

    Get-VM | Get-AdvancedSetting -Name *ctkEnabled* | Sort-Object Entity,Name |    Select Entity,Name,Value,Type | Export-Csv -NoTypeInformation -UseCulture c:\temp\advSettingInfo.csv
    

    Which will be, for any virtual computer that has a * ctkEnabled * advanced configuration, parameter information advanced output for such virtual machine to the CSV file in the appropriate location.  It relies on the ability to Get-AdvancedSetting to accept the VM objects as the value to - entity from the pipeline (so the foreach statement is not necessary) and used the - param Name of this cmdlet, avoiding any disorder Select-String.  I used Export-Csv to the output method so that you can easily consume these data later if you need to act on these data or even manipulate it.

    How does do for you?

  • 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.

  • 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.

  • 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.

Maybe you are looking for