I think I am trying to run before I can walk but I am trying to learn PS by creating a solution to a problem I have – best way to learn right?!
This is what I am trying to accomplish (utilising PowerCLI cmdlets as well):
1. connect to esxihost
1.1 specify (read-host) vswitch0 nics
1.2 specify (read-host) vswitch1 nics
2. check if vswitch0 exists
2.1 if exists create new portgroups
2.2 if it doesn't exists create vswitch0
2.3 add nics specified in 1.1 to vswitch0
2.4 go to 2.1
3. check if vswitch1 exists
3.1 if exists create new portgroups
3.2 if it doesn't exists create vswitch1
3.3 add nics specified in 1.1 to vswitch1
3.4 go to 3.1
$vmhost=Connect-VIServer 10.0.0.114 -User root -Password Password1 #connet to esxi host
$vswitch=Get-VirtualSwitch#get vswitches
[array]$vswitch0nics= (Read-Host"Enter vSwitc0 NICs - comma separated")#.Split(",") | %{$_.Trim()} #specify (read-host) vswitch0 nics
[array]$vswitch1nics= (Read-Host"Enter vSwitc1 NICs - comma separated")#.Split(",") | %{$_.Trim()} #specify (read-host) vswitch1 nics
if ($vswitch-notmatch"vSwitch0") #check if vswitch0 exists & if it doesn't exists create vswitch0 adding nics specified on line 3 to it
{
New-VirtualSwitch -VMHost $vmhost -Name vSwitch0 -Nic $vswitch0nics
}
elseif ($vswitch -match "vSwitch0") #if switch0 exists create new portgroups
{
New-VirtualPortGroup -VirtualSwitch $vswitch -Name Servers -VLanId 22 -Server $vmhost
New-VirtualPortGroup -VirtualSwitch $vswitch -Name Development -VLanId 122 -Server $vmhost
New-VirtualPortGroup -VirtualSwitch $vswitch -Name Testing -VLanId 143 -Server $vmhost
}
elseif ($vswitch -notmatch "vSwitch1") #check if vswitch1 exists & if it doesn't exists create vswitch1 adding nics specified on line 4 to it
{
New-VirtualSwitch-VMHost$vmhost-Name vSwitch1 -Nic$vswitch1nics
}
elseif ($vswitch-match"vSwitch1") #if switch1 exists create new portgroups
{
New-VirtualPortGroup-VirtualSwitch$vswitch-Name vMotion -VLanId 200 -Server$vmhost
}
else
{
Write-host"Finished"
}
`
I did read that if you have a lot of ifs you should use switches – and I am trying to figure those out.
But I am also trying to figure out how to implement "code blocks?"/loops/conditional loops – something that replaces "go to".
Thanks in advance!