Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 9, 2022 03:05 am GMT

Recursive Function to Find All Folder Paths in vCenter Server Inventory using PowerCLI

This is a PowerShell / PowerCLI script I wrote to find all folder paths in a vCenter Server Inventory. A recursive function walks through the entire folder tree, pushing and popping each encountered folder to a stack to generate each full path. The paths are stored in an ArrayList, which is finally output to a text file.

Code

    function build_folder_paths {
Param($folders)
foreach($folder in $folders) { # iterate through each folder
$stack.Push($folder.Name) # push this folder to the stack
$sub_folders = $folder | Get-Folder -type VM -norecursion # get the immediate sub-folders of this folder
$stack_array = $stack.ToArray() # convert the stack to an array
[array]::Reverse($stack_array) # reverse the array so the top of the stack has the highest index
$folder_path = $stack_array -join "/" # join the array with '/' to build the folder path
$folder_paths.Add($folder_path) # add the folder path to the arraylist
Write-Host("Folder Path: " + $folder_path)
if(!$sub_folders) { # if there are no sub-folders in this folder
try {
$stack.Pop() | Out-Null # then pop the stack
} catch {
Write-Host("Stack Empty.")
}
} else {
build_folder_paths($sub_folders) # else, build paths to sub-folders
}
}
try {
$stack.Pop() | Out-Null # pop parent folder
} catch {
Write-Host("Stack Empty.")
}
}
$folder_paths = New-Object -TypeName "System.Collections.ArrayList"         # for storing folder paths$stack = New-Object -TypeName "System.Collections.Stack"                    # for building folder paths$start_folders = Get-Folder VM -type VM | Get-Folder -type VM -norecursion  # get the immediate sub-folders of the root folderbuild_folder_paths($start_folders)                                          # build all folder paths$folder_paths | Out-File ./folder_paths.txt                                 # write all folder paths to file




Resources

VMware PowerCLI


Original Link: https://dev.to/thomaskcode/recursive-function-to-find-all-folder-paths-in-vcenter-server-inventory-using-powercli-4lg0

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To