PowerCLI

 View Only
Expand all | Collapse all

Export list of VMs with complete folder path

  • 1.  Export list of VMs with complete folder path

    Posted Feb 24, 2017 10:31 AM

    Hi all,

    I´m not a scripter so I need your help for my environemnt - 1 vcenter 5 datacenters without templates.

    I need an export in csv contains the BlueFolderPath, I found a lot of scripts using Get-Folder and Get-FolderPath (is not recognized as the name of a cmdlet) something like that but nothing is working.

    example CSV:

    AB
    testvm1DATACENTER\Applications\Banking\external
    testvm2DATACENTER\Applications\Banking
    testvm3DATACENTER\
    testvm4DATACENTER\Applications

    I found a lot of scripts from LucD but I think I´m to stuipd to get it to fly.

    Get the folderpath - LucD notes

    Folder by Path - LucD notes

    I hope someone can help me :smileysad:

    Thanks a lot

    Greetings



  • 2.  RE: Export list of VMs with complete folder path

    Posted Feb 24, 2017 11:07 AM

    What errors are you getting?

    Can you attach the script your are using, and preferably a screenshot of the run.



  • 3.  RE: Export list of VMs with complete folder path

    Posted Feb 24, 2017 01:25 PM

    do you have the snappin/module loaded? You should see VMware.VimAutomation.Core returned under either a get-pssnapin or get-module



  • 4.  RE: Export list of VMs with complete folder path

    Posted Feb 24, 2017 02:22 PM

    Oh damn, I´m such a script newby... I don´t read line 1 - -pssnapin VMware.VimAutomation.Core -version 4.1

    I want to use this script: Get the folderpath - LucD notes I think it´s the right one for me.

    How can I use version 4.1 when I have installed pCLI 6.5?

    Get-PowerCLIVersion

    PowerCLI Version
    ----------------
       VMware PowerCLI 6.5 Release 1 build 4624819
    ---------------
    Component Versions
    ---------------
       VMware Cis Core PowerCLI Component 6.5 build 4624453
       VMware VimAutomation Core PowerCLI Component 6.5 build 4624450
       VMWare ImageBuilder PowerCLI Component 6.5 build 4561891
       VMWare AutoDeploy PowerCLI Component 6.5 build 4561891
       VMware Vds PowerCLI Component 6.5 build 4624695
       VMware Cloud PowerCLI Component 6.5 build 4624821
       VMware HA PowerCLI Component 6.0 build 4525225
       VMware HorizonView PowerCLI Component 7.0.2 build 4596620
       VMware Licensing PowerCLI Component 6.5 build 4624822
       VMware PCloud PowerCLI Component 6.5 build 4624825
       VMware Storage PowerCLI Component 6.5 build 4624820
       VMware vROps PowerCLI Component 6.5 build 4624824
       VMware vSphere Update Manager PowerCLI 6.5 build 4540462



  • 5.  RE: Export list of VMs with complete folder path

    Posted Feb 24, 2017 02:41 PM

    You don't need 4.1, just remove that #requires line.

    It will work with 6.5R1 as well



  • 6.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 07:39 AM

    Good morning,

    I deleted the comments from the script. Now I get no error but the script is doing nothing. Should I put a Name of a folder in  HelpMessage = "Enter a folder")] ? Is it possible to dump it into a file?

    Must I use pCLI 6.0 when I use VMware 6.0U2 or should it also work with pCLI 6.5?

    When I use Get-Folder | Get-FolderPath I get an error - see attached picture.

    Thanks a lot for your help :smileygrin:



  • 7.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 07:43 AM

    I assume you have placed the function in that .ps1 file.

    In that case you need to dot-source it, like this

    . .\FolderPath.ps1

    There is a blank between the two dots.



  • 8.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 07:49 AM

    Yes the script is on my desktop in the "FolderPath.ps1".

    Empty screen also with ". .\FolderPath.ps1"



  • 9.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 08:03 AM

    The empty screen is normal.

    But is the function known, can you call it?



  • 10.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 09:32 AM

    Where is the output of the VMs/folder names?



  • 11.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 10:05 AM

    Now I'm confused, you execute 'Get-Command -Name Get-FolderPath' twice.

    One time it returns ok, the second call the function is not found anymore.

    Did you stop the PowerShell session in between?

    Did you dot-source the .ps1 file?

    The output of the function is displayed on the console

    .



  • 12.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 12:10 PM

    Now, I´m confused - must I need Windows PowerShell oder VMware Power CLI?



  • 13.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 12:23 PM

    Both!
    PowerCLI is an add-on on top of PowerShell.

    When you start the session from the PowerCLI shortcut, the PowerCLI initialisation script starts PowerShell and loads the required PSSnapin and/or modules (PSSnapin or modules depends on the PowerCLI version you have installed).

    From the PowerCLI prompt you can see that you are running PowerShell with PowerCLI loaded (6.5R1 in my case, which means only modules)..

    Once in the session, you can "load" functions that you have stored in .ps1 files, by dot-sourcing them.

    Once these functions are known to PowerShell, you can invoke them (see me previous answer).



  • 14.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 12:46 PM

    Get-Module show nothing:

    I don´t understand something...where is the output from the script?



  • 15.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 12:50 PM

    Oh my goooooooood.

    Now I understand your script - I can load it and use Get-FolderPath :smileyblush:

    So how can I create a dump to csv from the whole vcenter with this structure sorted by DC?

    AB
    testvm1DATACENTER\Applications\Banking\external
    testvm2DATACENTER\Applications\Banking
    testvm3DATACENTER\
    testvm4DATACENTER\Applications

    Something like that: Get-VM | Get-FolderPath?



  • 16.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 01:06 PM

    Just pipe the result to the Export-Csv cmdlet.

    Get-VM | Get-FolderPath | Export-Csv report.csv -NoTypeInformation -UseCulture



  • 17.  RE: Export list of VMs with complete folder path

    Posted Feb 27, 2017 02:49 PM

    I got this error by using Get-VM in combination with Get-FolderPath - both commands are working alone:



  • 18.  RE: Export list of VMs with complete folder path
    Best Answer

    Posted Feb 27, 2017 05:28 PM

    Sorry, I'm must have had a black out.

    The Get-FolderPath only works for Folder objects, not VM.

    But you can use the function from my Get-InventoryPlus – Inventory Of All VSphere Objects post.

    I attach a script that will list all the VMs, with their blue and yellow folder path.



  • 19.  RE: Export list of VMs with complete folder path

    Posted Feb 28, 2017 09:20 AM

    Hi LucD,

    wow great script and that is what I need.

    Is it possible to show only type = VirtualMachine that the script is running faster and the csv is not so big?

    Get-InventoryPlus | ? Type -eq VirtualMachine | Export-Csv -Path C:\temp\VMsrport.csv -NoTypeInformation -UseCulture

    I don´t know if i use the -eq right but my csv is empty. :smileysad:



  • 20.  RE: Export list of VMs with complete folder path

    Posted Feb 28, 2017 09:32 AM

    That should be ok.

    Are you connected to a vCenter?

    Is there anything in $global:defaultviservers



  • 21.  RE: Export list of VMs with complete folder path

    Posted Feb 28, 2017 09:47 AM

    I connect to the vCenter through pCLI with: Connect-VIServer -Server vCENTER and run then the script. Without the -eq I get a lot of output.

    Output of $global:defaultviservers is positiv with my vCENTER.



  • 22.  RE: Export list of VMs with complete folder path

    Posted Feb 28, 2017 10:03 AM

    Are there VirtualMachine entries in the output without the Where-clause?

    Which PowerShell version are you running?

    Do a $PSVersionTable



  • 23.  RE: Export list of VMs with complete folder path

    Posted Feb 28, 2017 11:15 AM

    Without -eq there was a lot of things in it - Ressources, Datacenter etc. but after 15 minutes running the script there was no VirtualMachine in the csv. and I stopped the script.

    Now I will run the script again during the lunch :smileyhappy:



  • 24.  RE: Export list of VMs with complete folder path

    Posted Feb 28, 2017 11:20 AM

    That's the latest PowerShell version, so you're good on that side.

    Depending on the size of your vSphere environment, the script might indeed run quite long.

    Don't you have a smaller test environment where you could test the validity of the script?

    Otherwise you'll have to wait for the run to cplete, and hope the PowerShell session doesn't run out of memory :-)



  • 25.  RE: Export list of VMs with complete folder path

    Posted Feb 28, 2017 11:29 AM

    I have only the big environment :smileysilly:

    How can I see if my pCLI is running out of memory?



  • 26.  RE: Export list of VMs with complete folder path

    Posted Feb 28, 2017 11:46 AM

    You can do

    Get-Process -Name powershell*

    Note that by default the PowerShell memory stack is limited, but there are ways to increase this.

    See for example Learn How to Configure PowerShell Memory



  • 27.  RE: Export list of VMs with complete folder path

    Posted Feb 28, 2017 12:55 PM

    Since 12:13pm script is running the csv is 214kb large :smileyhappy: and included "VirtualMachine" type with 1077 cells :smileycool:.

    Script is still running :smileyhappy:

    Finished: 1:57pm - csv 236kb - now I´m checking it!



  • 28.  RE: Export list of VMs with complete folder path

    Posted Feb 28, 2017 02:16 PM

    Great script it is to 99% perfect :smileyhappy:

    One question, is it possible to export the column "BluePath" and "Path" without the virtual machine name at the end or is it how VMware export it normally?



  • 29.  RE: Export list of VMs with complete folder path

    Posted Feb 28, 2017 02:38 PM

    Yes, that's possible, you'll have to change some lines.

    From the line numbers in my blog post Get-InventoryPlus – Inventory of all vSphere objects

    Replace line 51 and line 107 each with

          $path = @()



  • 30.  RE: Export list of VMs with complete folder path

    Posted Mar 03, 2017 09:24 AM

    Thanks a lot for your great help, now all is working! :smileyhappy:



  • 31.  RE: Export list of VMs with complete folder path

    Posted Jul 11, 2018 05:22 PM

    Hi LucD,

    Nice script!  Is there a way to use the Get-InventoryPlus function to just export from only one Datacenter within a vCenter?  We have multiple Datacenters and I want to only export VMs and folders from one DC.  Thanks in advance for your help.

    Tony



  • 32.  RE: Export list of VMs with complete folder path

    Posted Jul 11, 2018 06:00 PM

    That should be possible by changing the 1st parameter to the CreateContainerView method in line 155.

    I'll have to check, and update the function slightly.

    $contView = $viewMgr.CreateContainerView($si.Content.RootFolder,$null,$true)



  • 33.  RE: Export list of VMs with complete folder path

    Posted Jul 11, 2018 07:27 PM

    Ok, updated the function.

    Can you try the attached updated version?

    The inline help has been updated, and there are sample calls at the end of the file.



  • 34.  RE: Export list of VMs with complete folder path

    Posted Jul 12, 2018 04:20 PM

    Ran your new InventoryPlus script a few times against one of our vcenters with multiple vDCs and it worked great!  I modified lines 52 and 105 with $path = @() for cleaner output.  Thanks for script and your help!

    Tony



  • 35.  RE: Export list of VMs with complete folder path

    Posted Jul 24, 2018 03:56 PM

    Hi Luc,

    I had a quick question about modifying / using your function. My objective is to export a list of all VMs, their blue and yellow paths, and certain VM properties such as power state and host name.
    I am able to export the typical VM properties using "Get-VM | Select Name, PowerState, VMHost, VMHostId | Export-Csv -Path $csv -NoTypeInformation -UseCulture". I am also able to export your function's paths using "Get-InventoryPlus | where{$_.Type -eq 'VirtualMachine'} | Export-Csv -Path C:\Temp\Task1.csv -NoTypeInformation -UseCulture".

    However, I am unsure how to combine these. If it's not too much trouble, it'd be awesome if you could explain how to export a single csv file with columns for Name, Host, PowerState, BluePath, and YellowPath.


    P.S.: I'm relatively new to PowerShell and PowerCLI, so apologies if this is question is trivial. I came across this function the other day and really appreciate it! I also noticed you are the lead author of the PowerCLI Reference book, which is awesome!



  • 36.  RE: Export list of VMs with complete folder path

    Posted Dec 28, 2018 04:53 PM

    jeffreymcclain

    LucD

    Jeffery, did LucD help you with merging the folder information with the vm information? I'm looking for the same output so I can get users to authorize vm deletions. My column headers are:

    Folder

    Folder Path

    VM Name

    PowerState

    VMhost

    Uptime

    IP address(es)

    datastore

    vcentre (optional)

    I can do one or the other (folder vs vm information) and match up in Excel but that seems to be a waste of time. I'm just not sure of the code to use in powercli. Here's my gotcha as well...I'd like to do it for folders that contain a specific phrase such as "Wireless".



  • 37.  RE: Export list of VMs with complete folder path

    Posted Dec 28, 2018 05:36 PM

    Try like this

    function Get-InventoryPlus {

        <#

    .SYNOPSIS

    Retrieve the objects available on a vSphere Server.

    .DESCRIPTION

    This function will retrieve all objects available on a

    vSphere Server, including all storage and network objects.

    .NOTES

    Author:  Luc Dekens

    .PARAMETER Server

    The vSphere Server (vCenter or ESXi) from which to retrieve

    the objects.

    The default is $Global:DefaultVIServer

    .PARAMETER NoValue

    Properties that are not set are returned as an empty string.

    The value on this parameter will be used instead of the empty

    string.

    .PARAMETER RootObject

    A .Net PowerCLI object from where the inventory shall start

    .EXAMPLE

    PS> Get-InventoryPlus

    .EXAMPLE

    PS> Get-InventoryPlus -Server $vCenter

    .EXAMPLE

    PS> Get-InventoryPlus -NoValue 'na'

    .EXAMPLE

    PS> Get-InventoryPlus -RootObject (Get-Datacenter -Name DC1)

    #>

        [cmdletbinding()]

        param(

            [VMware.VimAutomation.ViCore.Types.V1.VIServer]$Server = $Global:DefaultVIServer,

            [String]$NoValue = '',

            [VMware.VimAutomation.ViCore.Types.V1.Inventory.InventoryItem]$RootObject

        )

        function Get-ViBlueFolderPath {

            [cmdletbinding()]

            param(

                [VMware.Vim.ManagedEntity]$Item

            )

            $hidden = 'Datacenters', 'vm'

            if ($Item -is [VMware.Vim.VirtualMachine]) {

                $Item.UpdateViewData('Parent')

                $parent = $Item.Parent

            }

            elseif ($Item -is [VMware.Vim.VirtualApp]) {

                $Item.UpdateViewData('ParentFolder')

                $parent = $Item.ParentFolder

            }

            if ($parent) {

                $path = @($Item.Name)

                while ($parent) {

                    $object = Get-View -Id $parent -Property Name, Parent

                    if ($hidden -notcontains $object.Name) {

                        $path += $object.Name

                    }

                    if ($object -is [VMware.Vim.VirtualApp]) {

                        $object.UpdateViewData('ParentFolder')

                        if ($object.ParentFolder) {

                            $parent = $object.ParentFolder

                        }

                        else {

                            $object.UpdateViewData('ParentVapp')

                            if ($object.ParentVapp) {

                                $parent = $object.ParentVapp

                            }

                        }

                    }

                    else {

                        $parent = $object.Parent

                    }

                }

                [array]::Reverse($path)

                return "/$($path -join '/')"

            }

            else {

                return $NoValue

            }

        }

        function Get-ObjectInfo {

            [cmdletbinding()]

            param(

                [parameter(ValueFromPipeline)]

                [VMware.Vim.ManagedEntity]$Object

            )

            Begin {

                $hidden = 'Datacenters', 'vm', 'host', 'network', 'datastore', 'Resources'

            }

            Process {

                if ($hidden -notcontains $Object.Name) {

                    $props = [ordered]@{

                        Name     = $Object.Name

                        Type     = $Object.GetType().Name

                        BluePath = $NoValue

                    }

                    $blueFolder = $false

                    $isTemplate = $false

                    if ($object -is [VMware.Vim.Folder]) {

                        $object.UpdateViewData('ChildType')

                        if ($Object.ChildType -contains 'VirtualMachine') {

                            $blueFolder = $true

                        }

                    }

                    $path = @($Object.Name)

                    $parent = $Object.Parent

                    if ($object -is [VMware.Vim.VirtualMachine] -or $object -is [VMware.Vim.VirtualApp]) {

                        $props['BluePath'] = Get-VIBlueFolderPath -Item $Object

                        if ($Object -is [VMware.Vim.VirtualMachine]) {

                            $Object.UpdateViewData('ResourcePool', 'Config.Template')

                            if ($Object.Config.Template) {

                                $parent = $Object.Parent

                                $props['Type'] = 'Template'

                                $isTemplate = $true

                            }

                            else {

                                $parent = $Object.ResourcePool

                            }

                        }

                    }

                    while ($parent) {

                        $Object = Get-View -Id $Parent -Property Name, Parent

                        $parent = $Object.Parent

                        if ($hidden -notcontains $Object.Name) {

                            $path += $Object.Name

                        }

                    }

                    [array]::Reverse($path)

                    $path = "/$($path -join '/')"

                    $props.Add('Path', $path)

                    if ($blueFolder) {

                        $props['BluePath'] = $props['Path']

                        $props['Path'] = $NoValue

                    }

                    if ($isTemplate) {

                        $props['Path'] = $NoValue

                    }

                    New-Object PSObject -Property $props

                }

            }

        }

        $sView = @{

            Id       = 'ServiceInstance'

            Server   = $Server

            Property = 'Content.ViewManager', 'Content.RootFolder'

        }

        $si = Get-view @sView

        if (-not $RootObject) {

            $RootMoRef = $si.Content.RootFolder

        }

        else {

            $RootMoRef = $RootObject.ExtensionData.MoRef

        }

        $viewMgr = Get-View -Id $si.Content.ViewManager

        $contView = $viewMgr.CreateContainerView($RootMoRef, $null, $true)

        $contViewObj = Get-View -Id $contView

        Get-View -Id $contViewObj.View -Property Name, Parent |

            Where-Object {$hidden -notcontains $_.Name} |

            Get-ObjectInfo

    }

    Get-InventoryPlus | where{$_.Type -eq 'VirtualMachine'} |

    ForEach-Object -Process {

        $vm = Get-VM $_.Name

        $_ | Add-Member -Name PowerSTate -Value $vm.PowerState -MemberType NoteProperty

        $_ | Add-Member -Name VMHost -Value $vm.VMHost.Name -MemberType NoteProperty

        $_ | Add-Member -Name Uptime -Value $vm.ExtensionData.Summary.QuickSTats.UptimeSeconds -MemberType NoteProperty

        $_ | Add-Member -Name IPAddress -Value ($vm.Guest.IPAddress -join '|') -MemberType NoteProperty

        $_ | Add-Member -Name Datastore -Value ((Get-View -Id $vm.DatastoreIdList -Property Name).Name -join '|') -MemberType NoteProperty

        $_ | Add-Member -Name vCenter -Value (([uri]$vm.ExtensionData.Client.ServiceUrl).Host) -MemberType NoteProperty

        $_

    }



  • 38.  RE: Export list of VMs with complete folder path

    Posted Dec 29, 2018 03:20 AM

    LucD​, that's almost exactly what I want. I've inserted the output below.

    1. I'm looking to limit it to a particular folder with wildcard (vCloud*) to shorten my results. I'm not sure how to insert that into the process.

    2. I would also like a bit of help understanding blue path vs yellow path. I've been reading your blog on Get-InventoryPlus and am not comprehending it.

    3. Uptime:  $_ | Add-Member -Name Uptime -Value $vm.ExtensionData.Summary.QuickSTats.UptimeSeconds ----> how do I get this rounded to days vs seconds?

    You've been a great teacher, Luc. I look forward to your reply.

    VMware_scripts> get-folder vClou*

    Name                               Type

    ----                                     ----

    vCloud (CG-ZZ)                 VM

    vCloud (CG-NL)                 VM



  • 39.  RE: Export list of VMs with complete folder path

    Posted Dec 29, 2018 05:19 AM

    1) The function supports a RootObject parameter, which is a starting point in your vSphere inventory from where to start the inventory.
    By passing all the selected folders (from the mask) one by one to the function, you get the inventory from all the folders.

    2) The yellow and blue stems from the fat vSphere Client.
    In short, yellow folders are the ones of type VM, blue are the ones of type HostAndCluster.
    It comes down to the fact that you can locate a VM in these 2 ways, once where it is located in the Datacenter-Cluster-VMHost hierarchy,
    and once via the VM and Templates view (Datacenter - Folder)

    3) With the TimeStamp type you can easily convert seconds into days.

    Only the last part needs some changes to implement 1) and 3)

    Get-Folder -Name vCloud* |

    ForEach-Object -Process {

        Get-InventoryPlus -RootObject $_ | where{$_.Type -eq 'VirtualMachine'} |

        ForEach-Object -Process {

            $vm = Get-VM $_.Name

            $_ | Add-Member -Name PowerSTate -Value $vm.PowerState -MemberType NoteProperty

            $_ | Add-Member -Name VMHost -Value $vm.VMHost.Name -MemberType NoteProperty

            $_ | Add-Member -Name UptimeDays -Value ([math]::Round(([TimeSpan]::FromSeconds($vm.ExtensionData.Summary.QuickSTats.UptimeSeconds)).TotalDays,0)) -MemberType NoteProperty

            $_ | Add-Member -Name IPAddress -Value ($vm.Guest.IPAddress -join '|') -MemberType NoteProperty

            $_ | Add-Member -Name Datastore -Value ((Get-View -Id $vm.DatastoreIdList -Property Name).Name -join '|') -MemberType NoteProperty

            $_ | Add-Member -Name vCenter -Value (([uri]$vm.ExtensionData.Client.ServiceUrl).Host) -MemberType NoteProperty

       

            $_

        }

    }



  • 40.  RE: Export list of VMs with complete folder path

    Posted Dec 31, 2018 02:18 PM

    Thank you, LucD , for the explanation and information regarding seconds to days. As always with your guidance, it worked like a charm.



  • 41.  RE: Export list of VMs with complete folder path

    Posted Dec 31, 2018 11:42 PM

    LucD , perhaps I spoke too soon.

    I modified your script slightly to capture sizing information. I also had to comment out the uptime field as it was occasionally generating an error (my apologies, I didn't capture it).

    I am concerned the script is stuck in a loop as it's been running for hours.

    Here's my script:

    #Report on vcloud vms - need users to decide what to do where there are duplicate names

    $report = @()

    Get-Folder -Name *|

    ForEach-Object -Process {

        Get-InventoryPlus -RootObject $_ | where{$_.Type -eq 'VirtualMachine'} |

        ForEach-Object -Process {

            $vm = Get-VM $_.Name

            $_ | Add-Member -Name PowerSTate -Value $vm.PowerState -MemberType NoteProperty

            $_ | Add-Member -Name OSName -Value $vm.guest.hostname -MemberType NoteProperty

            $_ | Add-Member -Name VMHost -Value $vm.VMHost.Name -MemberType NoteProperty

            #$_ | Add-Member -Name UptimeDays -Value ([math]::Round(([TimeSpan]::FromSeconds($vm.ExtensionData.Summary.QuickSTats.UptimeSeconds)).TotalDays,0)) -MemberType NoteProperty (paste word wrapped)

            $_ | Add-Member -Name IPAddress -Value ($vm.Guest.IPAddress -join '|') -MemberType NoteProperty

           

            $_ | Add-Member -Name Datastore -Value ((Get-View -Id $vm.DatastoreIdList -Property Name).Name -join '|') -MemberType NoteProperty

            $_ | Add-Member -Name VMid -Value $vm.id -MemberType NoteProperty

            $_ | Add-Member -Name MemoryMB -Value $vm.MemoryMB -MemberType NoteProperty

            $_ | Add-Member -Name NumCPU -Value $vm.NumCPU -MemberType NoteProperty

            $_ | Add-Member -Name UsedSpaceGB -Value $vm.UsedSpaceGB -MemberType NoteProperty

          

            $_ | Add-Member -Name vCenter -Value (([uri]$vm.ExtensionData.Client.ServiceUrl).Host) -MemberType NoteProperty

            #$_| Add-Member -Name Notes -Value ($vm.Notes) -MemberType NoteProperty

      

            $_

        }

    }

    $report



  • 42.  RE: Export list of VMs with complete folder path

    Posted Jan 01, 2019 12:01 AM

    LucD - randomly this pops up (see image). This is similar to what the math on uptime showed.



  • 43.  RE: Export list of VMs with complete folder path

    Posted Jan 01, 2019 12:33 AM

    The Get-InventoryPlus function re curses through the complete hierarchy starting from the RootObject.

    With Get-Folder -Name * you will be feeding all your folders one-by-one into the function, meaning that nested folders will be visited multiple times.

    Which could also explain the long runtime you see.

    A better option might be for example to start from all folders directly under a datacenter. For example:

    Get-Datacenter -Name MyDC | Get-Folder -Name * -NoRecursion |

    The error you are seeing might be coming from the fact that you have VMs with the same DisplayName in different folders.
    Is that case?
    If yes, we could fix that by using the full path and my Get-FolderByPath function.

    The script (minus the Get-InventoryPlus function) would then be

    function Get-FolderByPath{

    <#

    .SYNOPSIS Retrieve folders by giving a path

    .DESCRIPTION The function will retrieve a folder by it's path.

    The path can contain any type of leave (folder or datacenter).

    .NOTES Author: Luc Dekens

    .PARAMETER Path The path to the folder. This is a required parameter.

    .PARAMETER Separator The character that is used to separate the leaves

    in the path. The default is '/'

    .EXAMPLE

      PS> Get-FolderByPath -Path "Folder1/Datacenter/Folder2"

    .EXAMPLE

      PS> Get-FolderByPath -Path "Folder1>Folder2" -Separator '>'

    #>

      param(

      [CmdletBinding()]

      [parameter(Mandatory = $true)]

      [System.String[]]${Path},

      [char]${Separator} = '/'

      )

      process{

        if((Get-PowerCLIConfiguration).DefaultVIServerMode -eq "Multiple"){

          $vcs = $defaultVIServers

        }

        else{

          $vcs = $defaultVIServers[0]

        }

        foreach($vc in $vcs){

          foreach($strPath in $Path){

            $root = Get-Folder -Name Datacenters -Server $vc

            $strPath.Split($Separator) | %{

              $root = Get-Inventory -Name $_ -Location $root -Server $vc -NoRecursion

              if((Get-Inventory -Location $root -NoRecursion | Select -ExpandProperty Name) -contains "vm"){

                $root = Get-Inventory -Name "vm" -Location $root -Server $vc -NoRecursion

              }

            }

            $root | where {$_ -is [VMware.VimAutomation.ViCore.Impl.V1.Inventory.FolderImpl]}|%{

              Get-Folder -Name $_.Name -Location $root.Parent -NoRecursion -Server $vc

            }

          }

        }

      }

    }

    Get-Folder -Name linux* |

    ForEach-Object -Process {

        Get-InventoryPlus -RootObject $_ | where{$_.Type -eq 'VirtualMachine'} |

        ForEach-Object -Process {

            $qual = $_.BluePath.TrimStart('/').Split('/')

            $folder = Get-FolderByPath -Path ($qual[0..($qual.Count - 2)] -join '/')

            $vm = Get-VM $_.Name -Location $folder

            $_ | Add-Member -Name PowerSTate -Value $vm.PowerState -MemberType NoteProperty

            $_ | Add-Member -Name VMHost -Value $vm.VMHost.Name -MemberType NoteProperty

            $_ | Add-Member -Name UptimeDays -Value ([math]::Round(([TimeSpan]::FromSeconds($vm.ExtensionData.Summary.QuickSTats.UptimeSeconds)).TotalDays,0)) -MemberType NoteProperty

            $_ | Add-Member -Name IPAddress -Value ($vm.Guest.IPAddress -join '|') -MemberType NoteProperty

            $_ | Add-Member -Name Datastore -Value ((Get-View -Id $vm.DatastoreIdList -Property Name).Name -join '|') -MemberType NoteProperty

            $_ | Add-Member -Name vCenter -Value (([uri]$vm.ExtensionData.Client.ServiceUrl).Host) -MemberType NoteProperty

      

            $_

        }

    }



  • 44.  RE: Export list of VMs with complete folder path

    Posted Jan 02, 2019 05:22 PM

    LucD

    That makes sense and I'm willing to give it a go. However, I have several datacenters in my vcenter and I don't want to give it a go with the wrong ask, ie: a wildcard for the datacenter.

    Get-Datacenter -Name MyDC | Get-Folder -Name * -NoRecursion |

    --> I'd be entering Get-Datacenter -Name * | Get-Folder -Name * - NoRecursion. Seems like too many wildcards to me.



  • 45.  RE: Export list of VMs with complete folder path

    Posted Jan 02, 2019 05:34 PM

    Also, my VMs have unique VM names. They potentially have similar beginning characters of the VM names (container names) as shown in this example below. Is that what you mean by display names?



  • 46.  RE: Export list of VMs with complete folder path

    Posted Jan 02, 2019 05:41 PM

    The problem with the incorrect properties was due to the fact that you probably have folders with the same name.
    That is fixed by using the Get-FolderByPath function, that should only return 1 folder.

    I don't think there is a problem with the VM names, just the fact that there are folders with the same name in different locations.
    You can just start with Get-VM -Name *, and thanks to the Get-FolderByPath function, the previous folder related errors should be gone.

    The 2nd issue I mentioned is that Get-Folder -Name * (with the -NoRecursion), will return all folders (including children, grand-children...)
    Since Get-InventoryPlus also does a recursion, starting from the root or from the location specified on the RootObject parameter, you would end up with having the same inventory object multiple times in the report.



  • 47.  RE: Export list of VMs with complete folder path

    Posted Jan 02, 2019 08:56 PM

    LucD

    I'm noticing a random aside that likely makes no difference to my results.

    If the folder has a forward slash in it's name I get the following message. I'm not going to worry about it as my vm count is correct.

    If I had the cycles, I'd rename the folders with an acceptable character, but I'd want to do it with regular expressions vs one by one.EG: current name:Linux/Unix --> rename to Linux-Unix.  (if '/' is in the folder name replace with '-').



  • 48.  RE: Export list of VMs with complete folder path

    Posted Jan 02, 2019 09:52 PM

    Perhaps try replacing that line with

    $root = Get-Inventory -Name ($_ -replace '%2f','/') -Location $root -Server $vc -NoRecursion

    Changing the foldernames to eliminate the '/' isn't too hard.

    Depending on the vSphere version, you might have to look for/replace %2f instead of /

    Get-Folder | Set-Folder -Name ($_.Name -replace '%2f','-') -Confirm:$false



  • 49.  RE: Export list of VMs with complete folder path

    Posted Nov 16, 2022 10:38 AM

    What exactly is the blue and yellow folder types



  • 50.  RE: Export list of VMs with complete folder path

    Posted Nov 16, 2022 10:54 AM

    The colours are a relic of the past.
    The yellow folders are the ones under Hosts and Clusters (hidden folder host), the blue ones under VMs and Templates (hidden folder vm).