PS C:\script> # Values to be defined

$csvPath = '.\SIO-UFA2.csv '

$vlanlist = 7..9

$vssName = 'vSwitch2'

$netFolderBase = 'PEDAGO\GRETA'

function Get-PGMoRef {

    [cmdletbinding()]

    [OutputType([VMware.Vim.ManagedObjectReference])]

    param(

        [string]$VMHost,

        [string]$Portgroup

    )

    $esxNode = Get-VMHost -Name $VMHost

    (Get-View -Id $esxNode.ExtensionData.Network | where { $_.Name -eq $Portgroup }).MoRef

}

function New-PGPermission {

    [cmdletbinding()]

    param(

        [VMware.Vim.ManagedObjectReference]$PGMoRef,

        [string]$Principal,

        [string]$Role

    )

    $authMgr = Get-View AuthorizationManager

    $perm = New-Object VMware.Vim.Permission

    $perm.Entity = $pgMoRef

    $perm.RoleId = (Get-VIRole -Name $role).ExtensionData.RoleId

    $perm.Principal = $principal

    $perm.Group = $false

    $perm.Propagate = $false

    $authMgr.SetEntityPermissions($PGMoRef, @($perm))

}

function Invoke-CleanupNetworkFolder{

    [cmdletbinding()]

    param(

        [VMware.VimAutomation.ViCore.Types.V1.Inventory.Folder]$NetFolder,

        [string]$User

    )

    $folder = Get-Folder -Name $User -Location $netFolder -ErrorAction SilentlyContinue

    if ($folder) {

        if ($folder.ExtensionData.ChildEntity) {

            Get-View -Id $folder.ExtensionData.ChildEntity -PipelineVariable pg | where{$_ -is [VMware.Vim.Network]} |

            ForEach-Object -Process {

                Get-View -Id $pg.Host | Get-VIObjectByVIView |

                ForEach-Object -Process {

                    Get-VirtualPortGroup -VMHost $_ -Name $pg.Name -ErrorAction SilentlyContinue |

                    Remove-VirtualPortGroup -Confirm:$false

                }

            }

            $folder.ExtensionData.UpdateViewData()

            Write-Host -NoNewline "Wait for PG removal in $($folder.Name) "

            while ($folder.ExtensionData.ChildEntity) {

                sleep 1

                Write-Host -NoNewline '.'

                $folder.ExtensionData.UpdateViewData()

            }

            Write-Host ' Done'

        }

        Remove-Folder -Folder $folder -Confirm:$false

    }

}

# Loop over all users

Import-Csv -Path $csvPath -UseCulture -PipelineVariable row |

ForEach-Object -Process {

    # Extract required values

    $domain,$userName = $row.User.Split('/')

    $principal = "$domain\$userName"

    $dcName = "DATACENTER - $($domain)"

    $dc = Get-Datacenter -Name $dcName

    $cluster = Get-Cluster -Location $dcName

    # Get DC network folder

    $netFolder = Get-Folder -Location $dc -Name network

    $netFolderBase.Split('\') | ForEach-Object -Process {

        $netFolder = Get-Folder -Name $_ -Location $netFolder

    }

    # Clean up old folder and PGs, should they exist

    Invoke-CleanupNetworkFolder -NetFolder $netFolder -User $userName

    # Create network folder

    $folder = New-Folder -Name $userName -Location $netFolder

    # Assign permission on folder

    New-VIPermission -Entity $folder -Principal $principal -Role $roleName | Out-Null

    # Create all PG on all ESXi nodes

    Get-VMHost -Location $cluster -PipelineVariable esx |

    ForEach-Object -Process {

        $vss = Get-VirtualSwitch -Name $vssName -VMHost $esx

        $vlanlist | ForEach-Object -Process {

            # Create new portgroup

            $pgName = "$userName$_"

            $pg = New-VirtualPortGroup -Name $pgName -VirtualSwitch $vss -VLanId $_

            # Get PG MoRef

            $pgMoRef = Get-PGMoRef -Portgroup $pg.Name -VMHost $esx.Name

            Write-Host -NoNewline "Waiting for PG $($pg.Name) creation "

            while ($pgMoRef -eq $null) {

                $pgMoRef = Get-PGMoRef -Portgroup $pg.Name -VMHost $esx.Name

                sleep 1

                Write-Host -NoNewline '.'

            }

            Write-Host ' Done'

            # Move PG into Folder

            $folder.ExtensionData.MoveIntoFolder($pgMoRef)

            # Assign permission on PG

            New-PGPermission -PGMoRef $pgMoRef -Principal $principal -Role $roleName

        }

    }

}
New-VIPermission : Cannot validate argument on parameter 'Role'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:159 char:66
+ ... mission -Entity $folder -Principal $principal -Role $roleName | Out-N ...
+                                                         ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [New-VIPermission], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.NewVIPermission
 
Waiting for PG UFA2137 creation ......... Done
Get-VIRole : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:51 char:38
+     $perm.RoleId = (Get-VIRole -Name $role).ExtensionData.RoleId
+                                      ~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-VIRole], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.GetVIRole
 
Exception calling "SetEntityPermissions" with "2" argument(s): "The object or item referred to could not be found."
At line:59 char:5
+     $authMgr.SetEntityPermissions($PGMoRef, @($perm))
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException
 
Waiting for PG UFA2138 creation ........ Done
Get-VIRole : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:51 char:38
+     $perm.RoleId = (Get-VIRole -Name $role).ExtensionData.RoleId
+                                      ~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-VIRole], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.GetVIRole
 
Exception calling "SetEntityPermissions" with "2" argument(s): "The object or item referred to could not be found."
At line:59 char:5
+     $authMgr.SetEntityPermissions($PGMoRef, @($perm))
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException
 
Waiting for PG UFA2139 creation ................ Done
Get-VIRole : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:51 char:38
+     $perm.RoleId = (Get-VIRole -Name $role).ExtensionData.RoleId
+                                      ~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-VIRole], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.GetVIRole
 
Exception calling "SetEntityPermissions" with "2" argument(s): "The object or item referred to could not be found."
At line:59 char:5
+     $authMgr.SetEntityPermissions($PGMoRef, @($perm))
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException
 
Waiting for PG UFA2137 creation ..... Done
Get-VIRole : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:51 char:38
+     $perm.RoleId = (Get-VIRole -Name $role).ExtensionData.RoleId
+                                      ~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-VIRole], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.GetVIRole
 
Exception calling "SetEntityPermissions" with "2" argument(s): "The object or item referred to could not be found."
At line:59 char:5
+     $authMgr.SetEntityPermissions($PGMoRef, @($perm))
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException
 
Waiting for PG UFA2138 creation ...... Done
Get-VIRole : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:51 char:38
+     $perm.RoleId = (Get-VIRole -Name $role).ExtensionData.RoleId
+                                      ~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-VIRole], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.GetVIRole
 
Exception calling "SetEntityPermissions" with "2" argument(s): "The object or item referred to could not be found."
At line:59 char:5
+     $authMgr.SetEntityPermissions($PGMoRef, @($perm))
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException
 
Waiting for PG UFA2139 creation ..... Done
Get-VIRole : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:51 char:38
+     $perm.RoleId = (Get-VIRole -Name $role).ExtensionData.RoleId
+                                      ~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-VIRole], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.GetVIRole
 
Exception calling "SetEntityPermissions" with "2" argument(s): "The object or item referred to could not be found."
At line:59 char:5
+     $authMgr.SetEntityPermissions($PGMoRef, @($perm))
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException
 
Waiting for PG UFA2137 creation .......... Done
Get-VIRole : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:51 char:38
+     $perm.RoleId = (Get-VIRole -Name $role).ExtensionData.RoleId
+                                      ~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-VIRole], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.GetVIRole
 
Exception calling "SetEntityPermissions" with "2" argument(s): "The object or item referred to could not be found."
At line:59 char:5
+     $authMgr.SetEntityPermissions($PGMoRef, @($perm))
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException
 
Waiting for PG UFA2138 creation .......... Done
Get-VIRole : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:51 char:38
+     $perm.RoleId = (Get-VIRole -Name $role).ExtensionData.RoleId
+                                      ~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-VIRole], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.GetVIRole
 
Exception calling "SetEntityPermissions" with "2" argument(s): "The object or item referred to could not be found."
At line:59 char:5
+     $authMgr.SetEntityPermissions($PGMoRef, @($perm))
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException
 
Waiting for PG UFA2139 creation .................. Done
Get-VIRole : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:51 char:38
+     $perm.RoleId = (Get-VIRole -Name $role).ExtensionData.RoleId
+                                      ~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-VIRole], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.PermissionManagement.GetVIRole
 
Exception calling "SetEntityPermissions" with "2" argument(s): "The object or item referred to could not be found."
At line:59 char:5
+     $authMgr.SetEntityPermissions($PGMoRef, @($perm))
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : VimException

PS C:\script>