python pyVmomi 创建多级folder

解沈义
2023-12-01

https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/create_folder_in_datacenter.py
以上链接是官方demo,但不支持创建多级folder
将这个方法进行更改

def create_folder(content, host_folder, folder_name):
    host_folder.CreateFolder(folder_name)

使用这两个方法进行替换

def mkdir_task(base_obj, dir_name):
    try:
        return base_obj.CreateFolder(dir_name)
    except (vim.fault.InvalidName) as e:
        print(e)
        import sys
        sys.exit()


def create_folder(content, base_obj, folder_path):

    folder_path_parts = folder_path.strip('/').split('/')

    for path_part in folder_path_parts:
        if base_obj.childEntity:
            for y, child_obj in enumerate(base_obj.childEntity):
                if child_obj.name == path_part:
                    base_obj = child_obj
                    break
                elif y >= len(base_obj.childEntity)-1:
                    base_obj = mkdir_task(base_obj, path_part)
                    break
        else:
            base_obj = mkdir_task(base_obj, path_part)
 类似资料: