Hi trying to introduce error handling into my scripts but having difficulty in getting the results I expect. The below script should stop running when it finds the first error which is if the hostname doesn't exist. Is break a good choice?
Also DNS has to be present for the syslog to be set as otherwise it cant resolve the syslog host and errors, so I have introduced error handling here, I would like if error found to run the DNS entry function again.
[CmdletBinding()]
[Parameter (Mandatory=$True)]
Param (
$esx = (read-host "enter ESX Hostname"),
$credentials = (Get-Credential -UserName root -Message "Enter the ESXi root password"),
$syslog = (Read-Host "enter syslog server e.g udp://asyslogserver.corp.local"),
$dns1 = (Read-Host "enter First DNS ip"),
$dns2 = (read-host "enter Second DNS ip"),
$cluster = (read-host "enter cluster")
)
#
#
########################
#Add vmhost to vcenter
########################
Write-Host -ForegroundColor GREEN "Adding ESXi host $esxi to vCenter"
try{
Add-VMHost -Name $esx -Location $cluster -User $credentials.UserName -Password $credentials.GetNetworkCredential().Password -force -ErrorAction Stop
}
Catch
{
$errormessage = $_.Exception.Message
$FailedItem = $_Exception.ItemName
Write-Host -ForegroundColor Yellow "Check the VMHost is in DNS $errormessage $FailedItem"
Break
}
#########################
#Set DNS
#########################
function set-dns{
begin{
write-host -ForegroundColor GREEN "Adding DNS Entries $dns1,$dns2 on vmHost $esxi"
}
Process{
Get-VMHost $esx | Get-VMHostNetwork | Set-VMHostNetwork -DnsAddress $dns1,$dns2 -Confirm:$false
}
}
set-dns
######################
#Set syslog
######################
function set-syslog{
Write-Host -ForegroundColor GREEN "Set Syslog"
Process{
Get-VMHost $esx | Get-VMHostNetwork | Set-VMHostNetwork -DnsAddress $dns1,$dns2 -Confirm:$false
Set-VMHostSyslogserver -SysLogServer $syslog -SysLogServerPort 514 -VMHost $esx -ErrorAction Stop
}
Catch
{
$errormessage = $_.Exception.Message
$FailedItem = $_Exception.ItemName
Write-Host "DNS $errormessage $FailedItem"
set-dns
}
}