First I created a file like this (as you wish to read users and groups from csv file)
| users |
groups |
| user1 |
groupA |
| user2 |
groupA |
| user3 |
groupB |
Then I ran the script, all done
Connect-VIServer -Server vcenter.example.com
$entries = Import-Csv -Path ".\Desktop\1.csv"
$groupedData = $entries | Group-Object -Property groups
foreach ($group in $groupedData) {
$groupName = $group.Name
Write-Host $groupName
if (-not (Get-VIAccount -Group -Name $groupName -ErrorAction SilentlyContinue)) {
New-VIAccount -Group -Name $groupName -Domain "vsphere.local" # change domain if needed
Write-Host "Created group: $groupName"
}
foreach ($entry in $group.Group) {
$username = $entry.users
if (-not (Get-VIAccount -User -Name $username -ErrorAction SilentlyContinue)) {
New-VIAccount -User -Name $username -Domain "vsphere.local" -Password (Read-Host -Prompt "Password for $username" -AsSecureString)
Write-Host "Created user: $username"
}
Add-VIAccountToGroup -User $username -Group $groupName -Domain "vsphere.local"
Write-Host "Added $username to $groupName"
}
}