From 0ecc4f444856beeb711ef9e3b972d0834da50fd2 Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 22 Aug 2024 19:52:42 -0400 Subject: [PATCH] chore: simplify function names Changes the following non-exported function names: - `Write-PowerManagementLogMessage` >> `Write-LogMessage` - `Debug-CatchWriterForPowerManagement` >> `Write-DebugMessage` Signed-off-by: Ryan Johnson --- .../PowerManagement-ManagementDomain.ps1 | 421 +++++++------ .../PowerManagement-WorkloadDomain.ps1 | 364 ++++++----- VMware.CloudFoundation.PowerManagement.psm1 | 580 +++++++++--------- 3 files changed, 730 insertions(+), 635 deletions(-) diff --git a/SampleScripts/PowerManagement-ManagementDomain.ps1 b/SampleScripts/PowerManagement-ManagementDomain.ps1 index e99f0cb..42930fa 100644 --- a/SampleScripts/PowerManagement-ManagementDomain.ps1 +++ b/SampleScripts/PowerManagement-ManagementDomain.ps1 @@ -81,7 +81,7 @@ if(($PSBoundParameters.ContainsKey("shutdown") -or $PSBoundParameters.ContainsKe } # Error Handling (script scope function) -Function Debug-CatchWriterForPowerManagement { +Function Write-DebugMessage { Param ( [Parameter (Mandatory = $true)] [PSObject]$object ) @@ -89,9 +89,9 @@ Function Debug-CatchWriterForPowerManagement { $lineNumber = $object.InvocationInfo.ScriptLineNumber $lineText = $object.InvocationInfo.Line.trim() $errorMessage = $object.Exception.Message - Write-PowerManagementLogMessage -Type ERROR -Message " ERROR at Script Line $lineNumber" - Write-PowerManagementLogMessage -Type ERROR -Message " Relevant Command: $lineText" - Write-PowerManagementLogMessage -Type ERROR -Message " ERROR Message: $errorMessage" + Write-LogMessage -Type ERROR -Message " ERROR at Script Line $lineNumber" + Write-LogMessage -Type ERROR -Message " Relevant Command: $lineText" + Write-LogMessage -Type ERROR -Message " ERROR Message: $errorMessage" Write-Error -Message $errorMessage } @@ -99,7 +99,7 @@ Function Debug-CatchWriterForPowerManagement { Try { Clear-Host; Write-Host "" Start-SetupLogFile -Path $PSScriptRoot -ScriptName $MyInvocation.MyCommand.Name - Write-PowerManagementLogMessage -Type INFO -Message "Setting up the log file to path $logfile" + Write-LogMessage -Type INFO -Message "Setting up the log file to path $logfile" $Global:ProgressPreference = 'SilentlyContinue' if ($PsBoundParameters.ContainsKey("shutdown")) { if ($PsBoundParameters.ContainsKey("shutdownCustomerVm")) { $customerVmMessage = "Process WILL gracefully shutdown customer deployed Virtual Machines, if deployed within the Management Domain" } @@ -109,36 +109,36 @@ Try { $defaultFile = "./ManagementStartupInput.json" $inputFile = $null if ($json) { - Write-PowerManagementLogMessage -Type INFO -Message "The input JSON file provided." + Write-LogMessage -Type INFO -Message "The input JSON file provided." $inputFile = $json } elseif (Test-Path -Path $defaultFile -PathType Leaf) { - Write-PowerManagementLogMessage -Type INFO -Message "No path to JSON provided in the command line. Using the auto-created input file ManagementStartupInput.json in the current directory." + Write-LogMessage -Type INFO -Message "No path to JSON provided in the command line. Using the auto-created input file ManagementStartupInput.json in the current directory." $inputFile = $defaultFile } if ([string]::IsNullOrEmpty($inputFile)) { - Write-PowerManagementLogMessage -Type WARNING -Message "JSON input file is not provided. Cannot proceed! Exiting! " + Write-LogMessage -Type WARNING -Message "JSON input file is not provided. Cannot proceed! Exiting! " Exit } Write-Host "" $proceed = Read-Host "The following JSON file $inputFile will be used for the operation, please confirm (Yes or No)[default:No]" if (-Not $proceed) { - Write-PowerManagementLogMessage -Type WARNING -Message "None of the options is selected. Default is 'No', hence stopping script execution." + Write-LogMessage -Type WARNING -Message "None of the options is selected. Default is 'No', hence stopping script execution." Exit } else { if (($proceed -match "no") -or ($proceed -match "yes")) { if ($proceed -match "no") { - Write-PowerManagementLogMessage -Type WARNING -Message "Stopping script execution because the input is 'No'." + Write-LogMessage -Type WARNING -Message "Stopping script execution because the input is 'No'." Exit } } else { - Write-PowerManagementLogMessage -Type WARNING -Message "Pass the right string, either 'Yes' or 'No'." + Write-LogMessage -Type WARNING -Message "Pass the right string, either 'Yes' or 'No'." Exit } } - Write-PowerManagementLogMessage -Type INFO -Message "'$inputFile' is checked for correctness, proceeding with the execution." + Write-LogMessage -Type INFO -Message "'$inputFile' is checked for correctness, proceeding with the execution." } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } # Pre-Checks @@ -150,11 +150,11 @@ Try { if ($PsBoundParameters.ContainsKey("shutdownCustomerVm")) { $str2 = $str2 + " -shutdownCustomerVm" } if ($PsBoundParameters.ContainsKey("genjson")) { $str2 = $str2 + " -genjson" } if ($json) { $str2 = $str2 + " -json $json" } - Write-PowerManagementLogMessage -Type INFO -Message "Script used: $str1" - Write-PowerManagementLogMessage -Type INFO -Message "Script syntax: $str2" - if (-Not $null -eq $customerVmMessage) { Write-PowerManagementLogMessage -Type INFO -Message $customerVmMessage } + Write-LogMessage -Type INFO -Message "Script used: $str1" + Write-LogMessage -Type INFO -Message "Script syntax: $str2" + if (-Not $null -eq $customerVmMessage) { Write-LogMessage -Type INFO -Message $customerVmMessage } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ Exit } @@ -162,25 +162,25 @@ Try { if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKey("genjson")) { Try { # Check connection to SDDC Manager - Write-PowerManagementLogMessage -Type INFO -Message "Attempting to connect to VMware Cloud Foundation to gather system details." + Write-LogMessage -Type INFO -Message "Attempting to connect to VMware Cloud Foundation to gather system details." if (!(Test-EndpointConnection -server $server -Port 443)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot communicate with SDDC Manager ($server). Check the FQDN or IP address or the power state of '$server'." + Write-LogMessage -Type ERROR -Message "Cannot communicate with SDDC Manager ($server). Check the FQDN or IP address or the power state of '$server'." Exit } $statusMsg = Request-VCFToken -fqdn $server -username $user -password $pass -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ( $statusMsg ) { Write-PowerManagementLogMessage -Type INFO -Message $statusMsg } - if ( $warnMsg ) { Write-PowerManagementLogMessage -Type WARNING -Message $warnMsg } - if ( $errorMsg ) { Write-PowerManagementLogMessage -Type ERROR -Message $errorMsg } + if ( $statusMsg ) { Write-LogMessage -Type INFO -Message $statusMsg } + if ( $warnMsg ) { Write-LogMessage -Type WARNING -Message $warnMsg } + if ( $errorMsg ) { Write-LogMessage -Type ERROR -Message $errorMsg } if ($accessToken) { - Write-PowerManagementLogMessage -Type INFO -Message "Connection to SDDC Manager has been validated successfully." - Write-PowerManagementLogMessage -Type INFO -Message "Gathering system details from the SDDC Manager inventory. It will take some time." + Write-LogMessage -Type INFO -Message "Connection to SDDC Manager has been validated successfully." + Write-LogMessage -Type INFO -Message "Gathering system details from the SDDC Manager inventory. It will take some time." $workloadDomain = Get-VCFWorkloadDomain | Where-Object { $_.type -eq "MANAGEMENT" } # Check if we have single cluster in the MGMT domain $vcfVersion = Get-VCFManager | Select-Object version | Select-String -Pattern '\d+\.\d+' -AllMatches | ForEach-Object { $_.matches.groups[0].value } if ($workloadDomain.clusters.id.count -gt 1) { - Write-PowerManagementLogMessage -Type INFO -Message "More than one cluster exists in the management domain." + Write-LogMessage -Type INFO -Message "More than one cluster exists in the management domain." $mgmtClusterIds = @() $mgmtClusterIds = (Get-VCFWorkloadDomain | Select-Object Type -ExpandProperty clusters | Where-Object { $_.type -eq "MANAGEMENT" }).id foreach ($clusterId in $mgmtClusterIds) { @@ -189,10 +189,10 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe if (!$isDefault) { $answer = Read-Host -Prompt "Shutdown cluster $clusterNameExtra. Do you want to continue? Y/N" if ($answer -Match "N") { - Write-PowerManagementLogMessage -Type WARNING "Cancelling shutdown of $clusterName. Exiting..." + Write-LogMessage -Type WARNING "Cancelling shutdown of $clusterName. Exiting..." Exit } else { - Write-PowerManagementLogMessage -Type INFO "Shutting down $clusterName..." + Write-LogMessage -Type INFO "Shutting down $clusterName..." } # Shut Down the vSphere Cluster Services Virtual Machines $domain = Get-VCFWorkloadDomain | Select-Object name, type | Where-Object { $_.type -eq "MANAGEMENT" } @@ -219,49 +219,49 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe Set-Retreatmode -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass -cluster $clusterName -mode enable $counter = 0 $retries = 10 - Write-PowerManagementLogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS shutdown will take time. Please wait..." + Write-LogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS shutdown will take time. Please wait..." while ($counter -ne $retries) { if (Test-vSphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { $powerOnVMcount = (Get-VM -Location $clusterNameExtra | Where-Object { $_.name -match "vCLS" }).count if ( $powerOnVMcount ) { - Write-PowerManagementLogMessage -Type INFO -Message "Some vCLS virtual machines are still running. Sleeping for $sleepTime seconds until the next check..." + Write-LogMessage -Type INFO -Message "Some vCLS virtual machines are still running. Sleeping for $sleepTime seconds until the next check..." Start-Sleep -s $sleepTime Break } } } if ($counter -eq $retries) { - Write-PowerManagementLogMessage -Type ERROR -Message "vCLS virtual machines were not shut down within the expected time. Exiting... " + Write-LogMessage -Type ERROR -Message "vCLS virtual machines were not shut down within the expected time. Exiting... " Exit } # Stop vSphere HA to avoid "orphaned" VMs during vSAN shutdown if (Test-vSphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { if (!$(Set-VsphereHA -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass -cluster $clusterName -disableHA)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to disable vSphere High Availability for cluster '$clusterName'. Exiting..." + Write-LogMessage -Type ERROR -Message "Unable to disable vSphere High Availability for cluster '$clusterName'. Exiting..." Exit } } if (Test-vSphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { $remoteVMs = @() $remoteVMs = Get-PowerOnVMsOnRemoteDS $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass -clustertocheck $clusterName - Write-PowerManagementLogMessage -Type INFO -Message "All remote virtual machines are powered off." + Write-LogMessage -Type INFO -Message "All remote virtual machines are powered off." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Some remote virtual machines are still powered-on : $($remoteVMs.Name). Unable to proceed until these are are shutdown. Exiting..." + Write-LogMessage -Type ERROR -Message "Some remote virtual machines are still powered-on : $($remoteVMs.Name). Unable to proceed until these are are shutdown. Exiting..." Exit } # Testing VSAN health if ( (Test-VsanHealth -cluster $clusterNameExtra -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) -eq 0) { - Write-PowerManagementLogMessage -Type INFO -Message "vSAN cluster is in a healthy state." + Write-LogMessage -Type INFO -Message "vSAN cluster is in a healthy state." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "vSAN cluster is in an unhealthy state. Check the vSAN status in cluster '$($clusterName)'. Retry after resolving the vSAN health state. Exiting..." + Write-LogMessage -Type ERROR -Message "vSAN cluster is in an unhealthy state. Check the vSAN status in cluster '$($clusterName)'. Retry after resolving the vSAN health state. Exiting..." Exit } if ((Test-VsanObjectResync -cluster $clusterNameExtra -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) -eq 0) { - Write-PowerManagementLogMessage -Type INFO -Message "vSAN object resynchronization successful." + Write-LogMessage -Type INFO -Message "vSAN object resynchronization successful." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "vSAN object resynchronization is running. Retry after the vSAN object resynchronization is completed. Exiting..." + Write-LogMessage -Type ERROR -Message "vSAN object resynchronization is running. Retry after the vSAN object resynchronization is completed. Exiting..." Exit } # Checks SSH Status, if SSH service is not started, SSH will be started @@ -271,7 +271,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe $esxiHosts = (Get-VCFHost | Select-Object fqdn -ExpandProperty cluster | Where-Object { $_.id -eq $clusterId.id }).fqdn foreach ($esxi in $esxiHosts) { if (-Not (Test-VsphereConnection -server $esxiNode)) { - Write-PowerManagementLogMessage -Type ERROR "ESXi host $esxi is not accessible. Exiting..." + Write-LogMessage -Type ERROR "ESXi host $esxi is not accessible. Exiting..." Exit } else { $password = (Get-VCFCredential -resourceName $esxi | Select-Object password) @@ -279,34 +279,34 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe $status = Get-SSHEnabledStatus -server $esxi -user root -pass $esxiHostPassword if (-Not $status) { if (Test-vSphereAuthentication -server $esxi -user root -pass $esxiHostPassword) { - Write-PowerManagementLogMessage -Type WARNING "SSH is not enabled on ESXi host $esx. Enabling SSH..." + Write-LogMessage -Type WARNING "SSH is not enabled on ESXi host $esx. Enabling SSH..." Get-VmHostService -VMHost $esxi | Where-Object { $_.key -eq "TSM-SSH" } | Start-VMHostService Start-Sleep -s 10 - Write-PowerManagementLogMessage -Type INFO "Setting ESXi host $esxi to ignoreClusterMemberListUpdates..." + Write-LogMessage -Type INFO "Setting ESXi host $esxi to ignoreClusterMemberListUpdates..." Invoke-EsxCommand -server $esxi -user root -pass $esxiHostPassword -expected "Value of IgnoreClusterMemberListUpdates is 1" -cmd "esxcfg-advcfg -s 1 /VSAN/IgnoreClusterMemberListUpdates" } else { - Write-PowerManagementLogMessage -Type ERROR "Unable to authenticate to ESXi host $esxi. Exiting..." + Write-LogMessage -Type ERROR "Unable to authenticate to ESXi host $esxi. Exiting..." Exit } } else { if (Test-vSphereAuthentication -server $esxi -user root -pass $esxiHostPassword) { - Write-PowerManagementLogMessage -Type INFO "Setting ESXi host $esxi to ignoreClusterMemberListUpdates..." + Write-LogMessage -Type INFO "Setting ESXi host $esxi to ignoreClusterMemberListUpdates..." Invoke-EsxCommand -server $esxi -user root -pass $esxiHostPassword -expected "Value of IgnoreClusterMemberListUpdates is 1" -cmd "esxcfg-advcfg -s 1 /VSAN/IgnoreClusterMemberListUpdates" } else { - Write-PowerManagementLogMessage -Type ERROR "Unable to authenticate to ESXi host $esxi. Exiting..." + Write-LogMessage -Type ERROR "Unable to authenticate to ESXi host $esxi. Exiting..." Exit } } } } # Run vSAN cluster preparation on one ESXi host per cluster. - Write-PowerManagementLogMessage -Type INFO -Message "Pausing for 60 seconds before preparing ESXi hosts for vSAN shutdown..." + Write-LogMessage -Type INFO -Message "Pausing for 60 seconds before preparing ESXi hosts for vSAN shutdown..." Start-Sleep -s 60 $password = (Get-VCFCredential -resourceName $esxiHosts[0] | Select-Object password) $esxiHostPassword = $password.password[1] Invoke-EsxCommand -server $esxiHosts[0] -user root -pass $esxiHostPassword -expected "Cluster preparation is done" -cmd "python /usr/lib/vmware/vsan/bin/reboot_helper.py prepare" # Putting hosts in maintenance mode - Write-PowerManagementLogMessage -Type INFO -Message "Pausing for 30 seconds before putting ESXi hosts in maintenance mode..." + Write-LogMessage -Type INFO -Message "Pausing for 30 seconds before putting ESXi hosts in maintenance mode..." Start-Sleep -s 30 foreach ($esxiNode in $esxiHosts) { $password = (Get-VCFCredential -resourceName $esxi | Select-Object password) @@ -314,12 +314,12 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe Set-MaintenanceMode -server $esxiNode -user root -pass $esxiHostPassword -state ENABLE } # End of shutdown - Write-PowerManagementLogMessage -Type INFO -Message "End of the shutdown sequence!" - Write-PowerManagementLogMessage -Type INFO -Message "You can now shut down the ESXi hosts." + Write-LogMessage -Type INFO -Message "End of the shutdown sequence!" + Write-LogMessage -Type INFO -Message "You can now shut down the ESXi hosts." } else { # vSAN shutdown wizard automation. Set-VsanClusterPowerStatus -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass -cluster $clusterName -PowerStatus clusterPoweredOff -mgmt - Write-PowerManagementLogMessage -Type INFO -Message "Pausing for 60 seconds before checking ESXi hosts' shutdown status..." + Write-LogMessage -Type INFO -Message "Pausing for 60 seconds before checking ESXi hosts' shutdown status..." Start-Sleep -s 60 $counter = 0 $sleepTime = 60 # in seconds @@ -328,15 +328,15 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe # Verify all ESXi hosts are shut down to conclude the sequence foreach ($esxiNode in $esxiHosts) { if (Test-VsphereConnection -server $esxiNode) { - Write-PowerManagementLogMessage -Type WARNING -Message "Some ESXi hosts are still up. Pausing for $sleepTime seconds before next check..." + Write-LogMessage -Type WARNING -Message "Some ESXi hosts are still up. Pausing for $sleepTime seconds before next check..." Break } else { $successCount++ } } if ($successCount -eq $esxiWorkloadDomain.count) { - Write-PowerManagementLogMessage -Type INFO -Message "All ESXi hosts have been shut down successfully!" - Write-PowerManagementLogMessage -Type INFO -Message "Successfully completed the shutdown sequence!" + Write-LogMessage -Type INFO -Message "All ESXi hosts have been shut down successfully!" + Write-LogMessage -Type INFO -Message "Successfully completed the shutdown sequence!" Exit } else { Start-Sleep -s $sleepTime @@ -352,7 +352,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe } } } else { - Write-PowerManagementLogMessage -Type INFO -Message "A single cluster exists in the management domain." + Write-LogMessage -Type INFO -Message "A single cluster exists in the management domain." $cluster = Get-VCFCluster | Where-Object { $_.domain.id -eq $workloadDomain.id } } @@ -382,14 +382,14 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe # Test if the vCenter Server instance is reachable, if it is already stopped, do not continue with the shutdown sequence in automatic way. if (-Not (Test-EndpointConnection -server $vcServer.fqdn -Port 443) ) { - Write-PowerManagementLogMessage -Type WARNING -Message "Could not connect to $($vcServer.fqdn)! The script could not continue without a connection to the management vCenter Server. " - Write-PowerManagementLogMessage -Type ERROR -Message "Please check the current state and resolve the issue or continue with the shutdown operation by following the documentation of VMware Cloud Foundation. Exiting!" + Write-LogMessage -Type WARNING -Message "Could not connect to $($vcServer.fqdn)! The script could not continue without a connection to the management vCenter Server. " + Write-LogMessage -Type ERROR -Message "Please check the current state and resolve the issue or continue with the shutdown operation by following the documentation of VMware Cloud Foundation. Exiting!" Exit } $status = Get-TanzuEnabledClusterStatus -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name if ($status -eq $True) { - Write-PowerManagementLogMessage -Type ERROR -Message "Currently we are not supporting VMware Tanzu enabled domains. Exiting..." + Write-LogMessage -Type ERROR -Message "Currently we are not supporting VMware Tanzu enabled domains. Exiting..." Exit } @@ -467,7 +467,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe $var["NsxtManager"]["vipfqdn"] = $nsxtManagerFQDN $var["NsxtManager"]["nodes"] = $nsxtNodesFQDN $var["NsxtManager"]["user"] = $nsxtManagerVIP.adminUser - $var["NsxtManager"]["password"] = $nsxtManagerPassEncrypted + $var["NsxtManager"]["password"] = $nsxManagerPassEncrypted # Gather NSX-T Edge Node Details $nsxtManagerPowerOnVMs = 0 @@ -481,15 +481,18 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe } } if ($statusOfNsxtClusterVMs -ne 'running') { - Write-PowerManagementLogMessage -Type WARNING -Message "NSX Manager VMs have been stopped. NSX Edge VMs will not be handled automatically." + Write-LogMessage -Type WARNING -Message "NSX Manager VMs have been stopped. NSX Edge VMs will not be handled automatically." } else { Try { - Write-PowerManagementLogMessage -Type INFO -Message "NSX Manager VMs are in running state. Trying to fetch information about the NSX Edge VMs..." + Write-LogMessage -Type INFO -Message "NSX Manager VMs are in running state. Trying to fetch information about the NSX Edge VMs..." [Array]$edgeNodes = (Get-EdgeNodeFromNSXManager -server $nsxtManagerFQDN -user $nsxtManagerVIP.adminUser -pass $nsxtManagerVIP.adminPassword -VCfqdn $VcServer.fqdn) $edgeNodesToString = $edgeNodes -join "," - Write-PowerManagementLogMessage -Type INFO -Message "The NSX Edge VMs are $edgeNodesToString." + Write-LogMessage -Type INFO -Message "The NSX Edge VMs are $edgeNodesToString." } catch { - Write-PowerManagementLogMessage -Type ERROR -Message "Something went wrong! Cannot fetch NSX Edge nodes information from NSX Manager '$nsxtManagerFQDN'. Exiting!" + Write-LogMessage -Type ERROR -Message "Something went wrong! Cannot fetch NSX Edge nodes information from NSX Manager '$nsxtManagerFQDN'. Exiting!" + Write-LogMessage -Type INFO -Message "The NSX Edge VMs are $edgeNodesToString." + } Catch { + Write-LogMessage -Type ERROR -Message "Something went wrong! Cannot fetch NSX Edge nodes information from NSX Manager '$nsxtManagerFQDN'. Exiting!" } } @@ -509,7 +512,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe $vcHostUser = "" $vcHostPass = "" if ($vcServer.fqdn) { - Write-PowerManagementLogMessage -Type INFO -Message "Getting SDDC Manager VM name ..." + Write-LogMessage -Type INFO -Message "Getting SDDC Manager VM name ..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue | Out-Null } @@ -544,18 +547,18 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe if ($genjson) { if (Test-Path -Path "ManagementStartupInput.json" -PathType Leaf) { $location = Get-Location - Write-PowerManagementLogMessage -Type INFO -Message "#############################################################" - Write-PowerManagementLogMessage -Type INFO -Message "JSON generation is successful!" - Write-PowerManagementLogMessage -Type INFO -Message "ManagementStartupInput.json is created in the $location path." - Write-PowerManagementLogMessage -Type INFO -Message "#############################################################" + Write-LogMessage -Type INFO -Message "#############################################################" + Write-LogMessage -Type INFO -Message "JSON generation is successful!" + Write-LogMessage -Type INFO -Message "ManagementStartupInput.json is created in the $location path." + Write-LogMessage -Type INFO -Message "#############################################################" Exit } else { - Write-PowerManagementLogMessage -Type ERROR -Message "JSON file is not created. Check for permissions in the $location path" + Write-LogMessage -Type ERROR -Message "JSON file is not created. Check for permissions in the $location path" Exit } } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot obtain an access token from SDDC Manager ($server). Check your credentials." + Write-LogMessage -Type ERROR -Message "Cannot obtain an access token from SDDC Manager ($server). Check your credentials." Exit } @@ -567,16 +570,16 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe if (Test-VsphereConnection -server $esxiNode) { $status = Get-SSHEnabledStatus -server $esxiNode.fqdn -user $esxiNode.username -pass $esxiNode.password if (-Not $status) { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to establish an SSH connection to ESXi host $($esxiNode.fqdn). SSH is not enabled. Exiting..." + Write-LogMessage -Type ERROR -Message "Unable to establish an SSH connection to ESXi host $($esxiNode.fqdn). SSH is not enabled. Exiting..." Exit } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to connect to ESXi host $($esxiNode.fqdn). Exiting..." + Write-LogMessage -Type ERROR -Message "Unable to connect to ESXi host $($esxiNode.fqdn). Exiting..." Exit } } } Catch { - Write-PowerManagementLogMessage -Type ERROR -Message $_.Exception.Message + Write-LogMessage -Type ERROR -Message $_.Exception.Message Exit } } else { @@ -586,7 +589,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe foreach ($esxiNode in $esxiWorkloadDomain) { $HostConnectionState = Get-MaintenanceMode -server $esxiNode.fqdn -user $esxiNode.username -pass $esxiNode.password if ($HostConnectionState -eq "Maintenance") { - Write-PowerManagementLogMessage -Type ERROR -Message "$($esxiNode.fqdn) is in maintenance mode. Unable to shut down the cluster. Please take the host out of maintenance mode and run the script again." + Write-LogMessage -Type ERROR -Message "$($esxiNode.fqdn) is in maintenance mode. Unable to shut down the cluster. Please take the host out of maintenance mode and run the script again." Exit } } @@ -607,10 +610,10 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe if ($isPoweredOn -eq "PoweredOn") { $answer = Read-Host -Prompt "Workload domain vCenter Server instance $vm is powered on. Do you want to continue shutdown of the management domain? Y/N" if ($answer -Match 'N') { - Write-PowerManagementLogMessage -Type ERROR "Please shutdown the workload domain vCenter Server instance $vm and retry. Exiting..." + Write-LogMessage -Type ERROR "Please shutdown the workload domain vCenter Server instance $vm and retry. Exiting..." Exit } else { - Write-PowerManagementLogMessage -Type INFO "Continuing with the shutdown of the management domain." + Write-LogMessage -Type INFO "Continuing with the shutdown of the management domain." } } } @@ -621,28 +624,28 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe } } - Write-PowerManagementLogMessage -Type INFO -Message "Trying to fetch all powered-on virtual machines from server $($vcServer.fqdn)..." + Write-LogMessage -Type INFO -Message "Trying to fetch all powered-on virtual machines from server $($vcServer.fqdn)..." [Array]$allVMs = Get-VMsWithPowerStatus -powerstate "poweredon" -server $vcServer.fqdn -user $vcUser -pass $vcPass -silence $customerVMs = @() - Write-PowerManagementLogMessage -Type INFO -Message "Trying to fetch all powered-on vCLS virtual machines from server $($vcServer.fqdn)..." + Write-LogMessage -Type INFO -Message "Trying to fetch all powered-on vCLS virtual machines from server $($vcServer.fqdn)..." [Array]$vclsvms += Get-VMsWithPowerStatus -powerstate "poweredon" -server $vcServer.fqdn -user $vcUser -pass $vcPass -pattern "(^vCLS-\w{8}-\w{4}-\w{4}-\w{4}-\w{12})|(^vCLS\s*\(\d+\))|(^vCLS\s*$)" -silence foreach ($vm in $vclsvms) { [Array]$vcfVMs += $vm } - Write-PowerManagementLogMessage -Type INFO -Message "Fetching all powered on vSAN File Services virtual machines from vCenter Server instance $($vcenter)..." - [Array]$vsanFsVMs += Get-VMsWithPowerStatus -powerstate "poweredon" -server $vcServer.fqdn -user $vcUser -pass $vcPass -pattern "(vSAN File)" -silence + Write-LogMessage -Type INFO -Message "Fetching all powered on vSAN File Services virtual machines from vCenter Server instance $($vcenter)..." + [Array]$vsanFsVMs += Get-VMsWithPowerStatus -powerstate "poweredon" -server $vcServer.fqdn -user $vcUser -pass $vcPass -pattern "(vSAN File)" -silence foreach ($vm in $vsanFsVMs) { [Array]$vcfVMs += $vm } $customerVMs = $allVMs | Where-Object { $vcfVMs -notcontains $_ } $vcfVMs_string = $vcfVMs -join "; " - Write-PowerManagementLogMessage -Type INFO -Message "Management virtual machines covered by the script: '$($vcfVMs_string)' ." + Write-LogMessage -Type INFO -Message "Management virtual machines covered by the script: '$($vcfVMs_string)' ." if ($customerVMs.count -ne 0) { $customerVMs_string = $customerVMs -join "; " - Write-PowerManagementLogMessage -Type INFO -Message "Virtual machines not covered by the script: '$($customerVMs_string)' . Those VMs will be stopped in a random order if the 'shutdownCustomerVm' flag is passed." + Write-LogMessage -Type INFO -Message "Virtual machines not covered by the script: '$($customerVMs_string)' . Those VMs will be stopped in a random order if the 'shutdownCustomerVm' flag is passed." } # Check if VMware Tools are running in the customer VMs - if not we could not stop them gracefully @@ -653,12 +656,12 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue | Out-Null } if ( Test-EndpointConnection -server $vcServer.fqdn -Port 443 ) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$($vcServer.fqdn)' ..." + Write-LogMessage -Type INFO -Message "Connecting to '$($vcServer.fqdn)' ..." Connect-VIServer -Server $vcServer.fqdn -Protocol https -User $vcUser -Password $vcPass -ErrorVariable $vcConnectError | Out-Null if ($DefaultVIServer.Name -eq $vcServer.fqdn) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$($vcServer.fqdn)' and trying to get VMwareTools Status." + Write-LogMessage -Type INFO -Message "Connected to server '$($vcServer.fqdn)' and trying to get VMwareTools Status." foreach ($vm in $customerVMs) { - Write-PowerManagementLogMessage -Type INFO -Message "Checking VMwareTools Status for '$vm'..." + Write-LogMessage -Type INFO -Message "Checking VMwareTools Status for '$vm'..." $vm_data = Get-VM -Name $vm if ($vm_data.ExtensionData.Guest.ToolsRunningStatus -eq "guestToolsRunning") { [Array]$VMwareToolsRunningVMs += $vm @@ -667,7 +670,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe } } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to connect to vCenter Server '$($vcServer.fqdn)'. Command returned the following error: '$vcConnectError'." + Write-LogMessage -Type ERROR -Message "Unable to connect to vCenter Server '$($vcServer.fqdn)'. Command returned the following error: '$vcConnectError'." } } # Disconnect from the VC @@ -676,8 +679,8 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe } if ($VMwareToolsNotRunningVMs.count -ne 0) { $noToolsVMs = $VMwareToolsNotRunningVMs -join "; " - Write-PowerManagementLogMessage -Type WARNING -Message "There are some non VCF maintained VMs where VMwareTools NotRunning, hence unable to shutdown these VMs:'$noToolsVMs'." - Write-PowerManagementLogMessage -Type ERROR -Message "Unless these VMs are shutdown manually, we cannot proceed. Please shutdown manually and rerun the script." + Write-LogMessage -Type WARNING -Message "There are some non VCF maintained VMs where VMwareTools NotRunning, hence unable to shutdown these VMs:'$noToolsVMs'." + Write-LogMessage -Type ERROR -Message "Unless these VMs are shutdown manually, we cannot proceed. Please shutdown manually and rerun the script." Exit } } @@ -685,15 +688,15 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe if ($customerVMs.count -ne 0) { $customerVMs_string = $customerVMs -join "; " if ($PsBoundParameters.ContainsKey("shutdownCustomerVm")) { - Write-PowerManagementLogMessage -Type WARNING -Message "Some VMs are still in powered-on state. -shutdownCustomerVm is passed to the script." - Write-PowerManagementLogMessage -Type WARNING -Message "Hence shutting down VMs not managed by SDDC Manager to put the host in maintenance mode." - Write-PowerManagementLogMessage -Type WARNING -Message "The list of Non VCF management VMs: '$customerVMs_string'." + Write-LogMessage -Type WARNING -Message "Some VMs are still in powered-on state. -shutdownCustomerVm is passed to the script." + Write-LogMessage -Type WARNING -Message "Hence shutting down VMs not managed by SDDC Manager to put the host in maintenance mode." + Write-LogMessage -Type WARNING -Message "The list of Non VCF management VMs: '$customerVMs_string'." # Stop Customer VMs with one call to VC: Stop-CloudComponent -server $vcServer.fqdn -user $vcUser -pass $vcPass -nodes $customerVMs -timeout 300 } else { - Write-PowerManagementLogMessage -Type WARNING -Message "Some VMs are still in powered-on state. -shutdownCustomerVm is not passed to the script." - Write-PowerManagementLogMessage -Type WARNING -Message "Hence not shutting down management VMs not managed by SDDC Manager: $($customerVMs_string) ." - Write-PowerManagementLogMessage -Type ERROR -Message "The script cannot proceed unless these VMs are shut down manually or the -shutdownCustomerVm option is present. Take the necessary action and run the script again." + Write-LogMessage -Type WARNING -Message "Some VMs are still in powered-on state. -shutdownCustomerVm is not passed to the script." + Write-LogMessage -Type WARNING -Message "Hence not shutting down management VMs not managed by SDDC Manager: $($customerVMs_string) ." + Write-LogMessage -Type ERROR -Message "The script cannot proceed unless these VMs are shut down manually or the -shutdownCustomerVm option is present. Take the necessary action and run the script again." Exit } } @@ -711,7 +714,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe if (($vcfVcenterDetails = Get-vCenterServerDetail -server $server -user $user -pass $pass -domain $domain.name)) { if (Test-vSphereConnection -server $($vcfVcenterDetails.fqdn)) { if (Test-vSphereAuthentication -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) { - Write-PowerManagementLogMessage -Type INFO -Message "Stopping the VMware Aria Operations for Logs nodes..." + Write-LogMessage -Type INFO -Message "Stopping the VMware Aria Operations for Logs nodes..." Stop-CloudComponent -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass -nodes $vmList -timeout 600 } } @@ -748,17 +751,17 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe $vmName = $vm.Name $powerState = $vm.PowerState if ($powerState -eq "PoweredOn") { - Write-PowerManagementLogMessage -Type Error -Message "VM Name: $vmName, Power State: $powerState, Please power off the virtual machines connected to NSX Segments before you shutdown an NSX Edge Cluster" + Write-LogMessage -Type Error -Message "VM Name: $vmName, Power State: $powerState, Please power off the virtual machines connected to NSX Segments before you shutdown an NSX Edge Cluster" $stopExecuted = $true } if (-not $stopExecuted) { - Write-PowerManagementLogMessage -Type INFO -Message "Stopping the NSX Edge nodes..." + Write-LogMessage -Type INFO -Message "Stopping the NSX Edge nodes..." Stop-CloudComponent -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass -nodes $nsxtEdgeNodes -timeout 600 $stopExecuted = $true } } } else { - Write-PowerManagementLogMessage -Type WARNING -Message "No NSX Edge nodes present. Skipping shutdown..." + Write-LogMessage -Type WARNING -Message "No NSX Edge nodes present. Skipping shutdown..." } } } @@ -770,23 +773,23 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe } #Stop NSX Manager nodes - Write-PowerManagementLogMessage -Type INFO -Message "Stopping the NSX Manager nodes..." + Write-LogMessage -Type INFO -Message "Stopping the NSX Manager nodes..." Stop-CloudComponent -server $vcServer.fqdn -user $vcUser -pass $vcPass -nodes $nsxtNodes -timeout 600 #Check the vSAN health before SDDC manager is stopped if ( (Test-VsanHealth -cluster $cluster.name -server $vcServer.fqdn -user $vcUser -pass $vcPass) -eq 0) { - #Write-PowerManagementLogMessage -Type INFO -Message "vSAN cluster health is good." + #Write-LogMessage -Type INFO -Message "vSAN cluster health is good." } else { - Write-PowerManagementLogMessage -Type WARNING -Message "The vSAN cluster isn't in a healthy state. Check the vSAN cluster status in vCenter Server '$($vcServer.fqdn)'. After you resolve the vSAN health issues, run the script again." - Write-PowerManagementLogMessage -Type WARNING -Message "If the script has reached ESXi vSAN shutdown previously, this error is expected. Continue the shutdown workflow by following the documentation of VMware Cloud Foundation. " - Write-PowerManagementLogMessage -Type ERROR -Message "The vSAN cluster isn't in a healthy state. Check the messages above for a solution." + Write-LogMessage -Type WARNING -Message "The vSAN cluster isn't in a healthy state. Check the vSAN cluster status in vCenter Server '$($vcServer.fqdn)'. After you resolve the vSAN health issues, run the script again." + Write-LogMessage -Type WARNING -Message "If the script has reached ESXi vSAN shutdown previously, this error is expected. Continue the shutdown workflow by following the documentation of VMware Cloud Foundation. " + Write-LogMessage -Type ERROR -Message "The vSAN cluster isn't in a healthy state. Check the messages above for a solution." Exit } if ((Test-VsanObjectResync -cluster $cluster.name -server $vcServer.fqdn -user $vcUser -pass $vcPass) -eq 0) { - #Write-PowerManagementLogMessage -Type INFO -Message "vSAN object resynchronization is successful." + #Write-LogMessage -Type INFO -Message "vSAN object resynchronization is successful." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "vSAN object resynchronization is running. Stopping the script... Wait until the vSAN object resynchronization is completed and run the script again." + Write-LogMessage -Type ERROR -Message "vSAN object resynchronization is running. Stopping the script... Wait until the vSAN object resynchronization is completed and run the script again." Exit } @@ -798,14 +801,14 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe Set-Retreatmode -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -mode enable # Waiting for vCLS VMs to be stopped for ($retries*10) seconds - Write-PowerManagementLogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS shutdown will take time. Please wait!" + Write-LogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS shutdown will take time. Please wait!" $counter = 0 $retries = 10 $sleepTime = 30 while ($counter -ne $retries) { $powerOnVMcount = (Get-VMsWithPowerStatus -powerstate "poweredon" -server $vcServer.fqdn -user $vcUser -pass $vcPass -pattern "(^vCLS-\w{8}-\w{4}-\w{4}-\w{4}-\w{12})|(^vCLS\s*\(\d+\))|(^vCLS\s*$)").count if ( $powerOnVMcount ) { - Write-PowerManagementLogMessage -Type INFO -Message "Some vCLS VMs are still running. Sleeping for $sleepTime seconds until the next check..." + Write-LogMessage -Type INFO -Message "Some vCLS VMs are still running. Sleeping for $sleepTime seconds until the next check..." Start-Sleep -s $sleepTime $counter += 1 } else { @@ -813,7 +816,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe } } if ($counter -eq $retries) { - Write-PowerManagementLogMessage -Type ERROR -Message "The vCLS VMs were not shut down within the expected time. Stopping the script execution... " + Write-LogMessage -Type ERROR -Message "The vCLS VMs were not shut down within the expected time. Stopping the script execution... " Exit } @@ -821,7 +824,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe if ([float]$vcfVersion -le [float]4.5) { # Stop vSphere HA to avoid "orphaned" VMs during vSAN shutdown if (!$(Set-VsphereHA -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -disableHA)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Could not disable vSphere High Availability for cluster '$cluster'. Exiting!" + Write-LogMessage -Type ERROR -Message "Could not disable vSphere High Availability for cluster '$cluster'. Exiting!" } # Set DRS Automation Level to Manual in the Management Domain @@ -832,24 +835,24 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe $remoteVMs = @() $remoteVMs = Get-PowerOnVMsOnRemoteDS -server $vcServer.fqdn -user $vcUser -pass $vcPass -clustertocheck $cluster.name if ($remoteVMs.count -eq 0) { - Write-PowerManagementLogMessage -Type INFO -Message "All remote VMs are powered off." + Write-LogMessage -Type INFO -Message "All remote VMs are powered off." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Some remote VMs are still powered-on : $($remoteVMs.Name). Cannot proceed until the powered-on VMs are shut down. Check your environment." + Write-LogMessage -Type ERROR -Message "Some remote VMs are still powered-on : $($remoteVMs.Name). Cannot proceed until the powered-on VMs are shut down. Check your environment." } #Testing VSAN health after SDDC manager is stopped if ( (Test-VsanHealth -cluster $cluster.name -server $vcServer.fqdn -user $vcUser -pass $vcPass) -eq 0) { - Write-PowerManagementLogMessage -Type INFO -Message "vSAN cluster health is good." + Write-LogMessage -Type INFO -Message "vSAN cluster health is good." } else { - Write-PowerManagementLogMessage -Type WARNING -Message "The vSAN cluster isn't in a healthy state. Check the vSAN status in vCenter Server '$($vcServer.fqdn)'. After you resolve the vSAN issues, run the script again." - Write-PowerManagementLogMessage -Type WARNING -Message "If the script has reached ESXi vSAN shutdown previously, this error is expected. Continue by following the documentation of VMware Cloud Foundation. " - Write-PowerManagementLogMessage -Type ERROR -Message "The vSAN cluster isn't in a healthy state. Check the messages above for a solution." + Write-LogMessage -Type WARNING -Message "The vSAN cluster isn't in a healthy state. Check the vSAN status in vCenter Server '$($vcServer.fqdn)'. After you resolve the vSAN issues, run the script again." + Write-LogMessage -Type WARNING -Message "If the script has reached ESXi vSAN shutdown previously, this error is expected. Continue by following the documentation of VMware Cloud Foundation. " + Write-LogMessage -Type ERROR -Message "The vSAN cluster isn't in a healthy state. Check the messages above for a solution." Exit } if ((Test-VsanObjectResync -cluster $cluster.name -server $vcServer.fqdn -user $vcUser -pass $vcPass) -eq 0) { - Write-PowerManagementLogMessage -Type INFO -Message "VSAN object resynchronization is successful." + Write-LogMessage -Type INFO -Message "VSAN object resynchronization is successful." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "vSAN object resynchronization is running. Stopping the script. Wait until the vSAN object resynchronization is completed and run the script again." + Write-LogMessage -Type ERROR -Message "vSAN object resynchronization is running. Stopping the script. Wait until the vSAN object resynchronization is completed and run the script again." Exit } @@ -857,20 +860,20 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe # Verify that there is only one VM running (vCenter Server) on the ESXis, then shutdown vCenter Server. $runningVMs = Get-VMsWithPowerStatus -powerstate "poweredon" -server $vcServer.fqdn -user $vcUser -pass $vcPass -silence if ($runningVMs.count -gt 1 ) { - Write-PowerManagementLogMessage -Type WARNING -Message "Some VMs are still in powered-on state." - Write-PowerManagementLogMessage -Type WARNING -Message "Cannot proceed until the powered-on VMs are shut down. Shut them down them manually and continue with the shutdown operation by following documentation of VMware Cloud Foundation." - Write-PowerManagementLogMessage -Type ERROR -Message "There are running VMs in environment: $($runningVMs). Exiting! " + Write-LogMessage -Type WARNING -Message "Some VMs are still in powered-on state." + Write-LogMessage -Type WARNING -Message "Cannot proceed until the powered-on VMs are shut down. Shut them down them manually and continue with the shutdown operation by following documentation of VMware Cloud Foundation." + Write-LogMessage -Type ERROR -Message "There are running VMs in environment: $($runningVMs). Exiting! " } else { - Write-PowerManagementLogMessage -Type INFO -Message "There are no VMs in powered-on state. Hence, shutting down vCenter Server..." + Write-LogMessage -Type INFO -Message "There are no VMs in powered-on state. Hence, shutting down vCenter Server..." # Shutdown vCenter Server Stop-CloudComponent -server $vcHost -user $vcHostUser -pass $vcHostPass -pattern $vcServer.fqdn.Split(".")[0] -timeout 600 if (Get-VMRunningStatus -server $vcHost -user $vcHostUser -pass $vcHostPass -pattern $vcServer.fqdn.Split(".")[0] -Status "Running") { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot stop vCenter Server on the host. Exiting!" + Write-LogMessage -Type ERROR -Message "Cannot stop vCenter Server on the host. Exiting!" } } } # Verify that there are no running VMs on the ESXis and shutdown the vSAN cluster. - Write-PowerManagementLogMessage -Type INFO -Message "Checking that there are no running VMs on the ESXi hosts before stopping vSAN." + Write-LogMessage -Type INFO -Message "Checking that there are no running VMs on the ESXi hosts before stopping vSAN." $runningVMsPresent = $False $runningVMs = @() $runningVclsVMs = @() @@ -884,15 +887,15 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe $runningVMs = $runningAllVMs | Where-Object { $runningVclsVMs -notcontains $_ } } if ($runningVMs.count) { - Write-PowerManagementLogMessage -Type WARNING -Message "Some VMs are still in powered-on state." - Write-PowerManagementLogMessage -Type WARNING -Message "Cannot proceed until the powered-on VMs are shut down. Shut down them down manually and run the script again." - Write-PowerManagementLogMessage -Type WARNING -Message "ESXi with VMs running: $($esxiNode.fqdn) VMs are:$($runningVMs) " + Write-LogMessage -Type WARNING -Message "Some VMs are still in powered-on state." + Write-LogMessage -Type WARNING -Message "Cannot proceed until the powered-on VMs are shut down. Shut down them down manually and run the script again." + Write-LogMessage -Type WARNING -Message "ESXi with VMs running: $($esxiNode.fqdn) VMs are:$($runningVMs) " $runningVMsPresent = $True } } # Verify that there are no running VMs on the ESXis and shutdown the vSAN cluster. if ($runningVMsPresent) { - Write-PowerManagementLogMessage -Type ERROR -Message "Some VMs on the ESXi hosts are still in powered-on state. Check the console log, stop the VMs and continue the shutdown operation manually." + Write-LogMessage -Type ERROR -Message "Some VMs on the ESXi hosts are still in powered-on state. Check the console log, stop the VMs and continue the shutdown operation manually." } # Actual vSAN and ESXi shutdown happens here - once we are sure that there are no VMs running on hosts else { @@ -903,24 +906,24 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe } # Run vSAN cluster preparation - should be done on one host per cluster # Sleeping 1 min before starting the preparation - Write-PowerManagementLogMessage -Type INFO -Message "Sleeping for 60 seconds before preparing hosts for vSAN shutdown..." + Write-LogMessage -Type INFO -Message "Sleeping for 60 seconds before preparing hosts for vSAN shutdown..." Start-Sleep -s 60 Invoke-EsxCommand -server $esxiWorkloadDomain.fqdn[0] -user $esxiWorkloadDomain.username[0] -pass $esxiWorkloadDomain.password[0] -expected "Cluster preparation is done" -cmd "python /usr/lib/vmware/vsan/bin/reboot_helper.py prepare" # Putting hosts in maintenance mode - Write-PowerManagementLogMessage -Type INFO -Message "Sleeping for 30 seconds before putting hosts in maintenance mode..." + Write-LogMessage -Type INFO -Message "Sleeping for 30 seconds before putting hosts in maintenance mode..." Start-Sleep -s 30 foreach ($esxiNode in $esxiWorkloadDomain) { Set-MaintenanceMode -server $esxiNode.fqdn -user $esxiNode.username -pass $esxiNode.password -state ENABLE } # End of shutdown - Write-PowerManagementLogMessage -Type INFO -Message "End of the shutdown sequence!" - Write-PowerManagementLogMessage -Type INFO -Message "Shut down the ESXi hosts!" + Write-LogMessage -Type INFO -Message "End of the shutdown sequence!" + Write-LogMessage -Type INFO -Message "Shut down the ESXi hosts!" } else { # vSAN shutdown wizard automation. Set-VsanClusterPowerStatus -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -PowerStatus clusterPoweredOff -mgmt - Write-PowerManagementLogMessage -Type INFO -Message "Sleeping for 60 seconds before checking ESXi hosts' shutdown status..." + Write-LogMessage -Type INFO -Message "Sleeping for 60 seconds before checking ESXi hosts' shutdown status..." Start-Sleep -s 60 $counter = 0 @@ -932,15 +935,15 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe #Verify if all ESXi hosts are down in here to conclude End of Shutdown sequence foreach ($esxiNode in $esxiWorkloadDomain) { if (Test-EndpointConnection -server $esxiNode.fqdn -Port 443) { - Write-PowerManagementLogMessage -Type WARNING -Message "Some hosts are still up. '$($esxiNode.fqdn)' responded. Sleeping for 60 seconds before next check..." + Write-LogMessage -Type WARNING -Message "Some hosts are still up. Sleeping for 60 seconds before next check..." break } else { $successCount++ } } if ($successCount -eq $esxiWorkloadDomain.count) { - Write-PowerManagementLogMessage -Type INFO -Message "All hosts have been shut down successfully!" - Write-PowerManagementLogMessage -Type INFO -Message "End of the shutdown sequence!" + Write-LogMessage -Type INFO -Message "All hosts have been shut down successfully!" + Write-LogMessage -Type INFO -Message "End of the shutdown sequence!" Exit } else { Start-Sleep -s $sleepTime @@ -950,7 +953,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe } } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ Exit } } @@ -960,7 +963,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe if ($PsBoundParameters.ContainsKey("startup")) { Try { $MgmtInput = Get-Content -Path $inputFile | ConvertFrom-Json - Write-PowerManagementLogMessage -Type INFO -Message "Gathering system details from JSON file..." + Write-LogMessage -Type INFO -Message "Gathering system details from JSON file..." # Gather Details from SDDC Manager $workloadDomain = $MgmtInput.Domain.name $cluster = New-Object -TypeName PSCustomObject @@ -1034,29 +1037,29 @@ if ($PsBoundParameters.ContainsKey("startup")) { # Startup workflow starts here # Check if VC is running - if so, skip ESXi operations if (-Not (Test-EndpointConnection -server $vcServer.fqdn -Port 443 -WarningAction SilentlyContinue )) { - Write-PowerManagementLogMessage -Type INFO -Message "Could not connect to $($vcServer.fqdn). Starting vSAN..." + Write-LogMessage -Type INFO -Message "Could not connect to $($vcServer.fqdn). Starting vSAN..." if ([float]$vcfVersion -gt [float]4.4) { #TODO add check if hosts are up and running. If so, do not display this message Write-Host "" $proceed = Read-Host "Please start all the ESXi host belonging to the cluster '$($cluster.name)' and wait for the host console to come up. Once done, please enter yes." if (-Not $proceed) { - Write-PowerManagementLogMessage -Type WARNING -Message "None of the options is selected. Default is 'No', hence, stopping script execution..." + Write-LogMessage -Type WARNING -Message "None of the options is selected. Default is 'No', hence, stopping script execution..." Exit } else { if (($proceed -match "no") -or ($proceed -match "yes")) { if ($proceed -match "no") { - Write-PowerManagementLogMessage -Type WARNING -Message "Stopping script execution because the input is 'No'..." + Write-LogMessage -Type WARNING -Message "Stopping script execution because the input is 'No'..." Exit } } else { - Write-PowerManagementLogMessage -Type WARNING -Message "Pass the right string - either 'Yes' or 'No'." + Write-LogMessage -Type WARNING -Message "Pass the right string - either 'Yes' or 'No'." Exit } } foreach ($esxiNode in $esxiWorkloadDomain) { if (!(Test-EndpointConnection -server $esxiNode.fqdn -Port 443)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot communicate with host $($esxiNode.fqdn). Check the FQDN or IP address, or the power state of '$($esxiNode.fqdn)'." + Write-LogMessage -Type ERROR -Message "Cannot communicate with host $($esxiNode.fqdn). Check the FQDN or IP address, or the power state of '$($esxiNode.fqdn)'." Exit } } @@ -1067,16 +1070,16 @@ if ($PsBoundParameters.ContainsKey("startup")) { if (Test-VsphereConnection -server $esxiNode) { $status = Get-SSHEnabledStatus -server $esxiNode.fqdn -user $esxiNode.username -pass $esxiNode.password if (-Not $status) { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to establish an SSH connection to ESXi host $($esxiNode.fqdn). SSH is not enabled. Exiting..." + Write-LogMessage -Type ERROR -Message "Unable to establish an SSH connection to ESXi host $($esxiNode.fqdn). SSH is not enabled. Exiting..." Exit } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to connect to ESXi host $($esxiNode.fqdn). Exiting..." + Write-LogMessage -Type ERROR -Message "Unable to connect to ESXi host $($esxiNode.fqdn). Exiting..." Exit } } } Catch { - Write-PowerManagementLogMessage -Type ERROR -Message $_.Exception.Message + Write-LogMessage -Type ERROR -Message $_.Exception.Message Exit } @@ -1088,18 +1091,18 @@ if ($PsBoundParameters.ContainsKey("startup")) { if ([float]$vcfVersion -lt [float]4.5) { # Prepare the vSAN cluster for startup - Performed on a single host only # We need some time before this step, setting hard sleep 30 sec - Write-PowerManagementLogMessage -Type INFO -Message "Sleeping for 30 seconds before starting vSAN..." + Write-LogMessage -Type INFO -Message "Sleeping for 30 seconds before starting vSAN..." Start-Sleep -s 30 Invoke-EsxCommand -server $esxiWorkloadDomain.fqdn[0] -user $esxiWorkloadDomain.username[0] -pass $esxiWorkloadDomain.password[0] -expected "Cluster reboot/poweron is completed successfully!" -cmd "python /usr/lib/vmware/vsan/bin/reboot_helper.py recover" # We need some time before this step, setting hard sleep 30 sec - Write-PowerManagementLogMessage -Type INFO -Message "Sleeping for 30 seconds before enabling vSAN updates..." + Write-LogMessage -Type INFO -Message "Sleeping for 30 seconds before enabling vSAN updates..." Start-Sleep -s 30 foreach ($esxiNode in $esxiWorkloadDomain) { Invoke-EsxCommand -server $esxiNode.fqdn -user $esxiNode.username -pass $esxiNode.password -expected "Value of IgnoreClusterMemberListUpdates is 0" -cmd "esxcfg-advcfg -s 0 /VSAN/IgnoreClusterMemberListUpdates" } - Write-PowerManagementLogMessage -Type INFO -Message "Checking vSAN status of the ESXi hosts." + Write-LogMessage -Type INFO -Message "Checking vSAN status of the ESXi hosts." foreach ($esxiNode in $esxiWorkloadDomain) { Invoke-EsxCommand -server $esxiNode.fqdn -user $esxiNode.username -pass $esxiNode.password -expected "Local Node Health State: HEALTHY" -cmd "esxcli vsan cluster get" } @@ -1109,18 +1112,18 @@ if ($PsBoundParameters.ContainsKey("startup")) { Start-Sleep -s 5 if (-Not (Get-VMRunningStatus -server $vcHost -user $vcHostUser -pass $vcHostPass -pattern $vcServer.fqdn.Split(".")[0] -Status "Running")) { - Write-PowerManagementLogMessage -Type Warning -Message "Cannot start vCenter Server on the host. Check if vCenter Server is located on host $vcHost. " - Write-PowerManagementLogMessage -Type Warning -Message "Start vCenter Server manually and run the script again." - Write-PowerManagementLogMessage -Type ERROR -Message "Could not start vCenter Server on host $vcHost. Check the console log for more details." + Write-LogMessage -Type Warning -Message "Cannot start vCenter Server on the host. Check if vCenter Server is located on host $vcHost. " + Write-LogMessage -Type Warning -Message "Start vCenter Server manually and run the script again." + Write-LogMessage -Type ERROR -Message "Could not start vCenter Server on host $vcHost. Check the console log for more details." Exit } } } else { - Write-PowerManagementLogMessage -Type INFO -Message "vCenter Server '$($vcServer.fqdn)' is running. Skipping vSAN startup!" + Write-LogMessage -Type INFO -Message "vCenter Server '$($vcServer.fqdn)' is running. Skipping vSAN startup!" } # Wait till VC is started, continue if it is already up and running - Write-PowerManagementLogMessage -Type INFO -Message "Waiting for the vCenter Server services on $($vcServer.fqdn) to start..." + Write-LogMessage -Type INFO -Message "Waiting for the vCenter Server services on $($vcServer.fqdn) to start..." $retries = 20 if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue | Out-Null @@ -1134,20 +1137,20 @@ if ($PsBoundParameters.ContainsKey("startup")) { if ($status -eq "STARTED") { break } else { - Write-PowerManagementLogMessage -Type INFO -Message "The services on vCenter Server are still starting. Please wait. Sleeping for 60 seconds..." + Write-LogMessage -Type INFO -Message "The services on vCenter Server are still starting. Please wait. Sleeping for 60 seconds..." Start-Sleep -s 60 } } Disconnect-VIServer * -Force -Confirm:$false -WarningAction SilentlyContinue | Out-Null break } - Write-PowerManagementLogMessage -Type INFO -Message "The vCenter Server API is still not accessible. Please wait. Sleeping for 60 seconds..." + Write-LogMessage -Type INFO -Message "The vCenter Server API is still not accessible. Please wait. Sleeping for 60 seconds..." Start-Sleep -s 60 $retries -= 1 } # Check if VC have been started in the above time period if (!$retries) { - Write-PowerManagementLogMessage -Type ERROR -Message "Timeout while waiting vCenter Server to start. Exiting!" + Write-LogMessage -Type ERROR -Message "Timeout while waiting vCenter Server to start. Exiting!" } #Restart Cluster Via Wizard @@ -1159,12 +1162,12 @@ if ($PsBoundParameters.ContainsKey("startup")) { } # Check vSAN Status if ( (Test-VsanHealth -cluster $cluster.name -server $vcServer.fqdn -user $vcUser -pass $vcPass) -ne 0) { - Write-PowerManagementLogMessage -Type ERROR -Message "vSAN cluster health is bad. Check your environment and run the script again." + Write-LogMessage -Type ERROR -Message "vSAN cluster health is bad. Check your environment and run the script again." Exit } # Check vSAN Status if ( (Test-VsanObjectResync -cluster $cluster.name -server $vcServer.fqdn -user $vcUser -pass $vcPass) -ne 0) { - Write-PowerManagementLogMessage -Type ERROR -Message "vSAN object resynchronization is in progress. Check your environment and run the script again." + Write-LogMessage -Type ERROR -Message "vSAN object resynchronization is in progress. Check your environment and run the script again." Exit } @@ -1172,12 +1175,12 @@ if ($PsBoundParameters.ContainsKey("startup")) { if ([float]$vcfVersion -lt [float]4.5) { # Start vSphere HA if (!$(Set-VsphereHA -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -enableHA)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Could not enable vSphere High Availability for cluster '$cluster'." + Write-LogMessage -Type ERROR -Message "Could not enable vSphere High Availability for cluster '$cluster'." } # Restore the DRS Automation Level to the mode backed up for Management Domain Cluster during shutdown if ([string]::IsNullOrEmpty($drsAutomationLevel)) { - Write-PowerManagementLogMessage -Type ERROR -Message "The DrsAutomationLevel value in the JSON file is empty. Exiting!" + Write-LogMessage -Type ERROR -Message "The DrsAutomationLevel value in the JSON file is empty. Exiting!" Exit } else { Set-DrsAutomationLevel -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -level $drsAutomationLevel @@ -1187,14 +1190,14 @@ if ($PsBoundParameters.ContainsKey("startup")) { # Startup the vSphere Cluster Services Virtual Machines in the Management Workload Domain Set-Retreatmode -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -mode disable # Waiting for vCLS VMs to be started for ($retries*10) seconds - Write-PowerManagementLogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS virtual machines startup will take some time. Please wait." + Write-LogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS virtual machines startup will take some time. Please wait." $counter = 0 $retries = 10 $sleepTime = 30 while ($counter -ne $retries) { $powerOnVMcount = (Get-VMsWithPowerStatus -powerstate "poweredon" -server $vcServer.fqdn -user $vcUser -pass $vcPass -pattern "(^vCLS-\w{8}-\w{4}-\w{4}-\w{4}-\w{12})|(^vCLS\s*\(\d+\))|(^vCLS\s*$)" -silence).count if ( $powerOnVMcount -lt 3 ) { - Write-PowerManagementLogMessage -Type INFO -Message "There are $powerOnVMcount vCLS virtual machines running. Sleeping for $sleepTime seconds until the next check." + Write-LogMessage -Type INFO -Message "There are $powerOnVMcount vCLS virtual machines running. Sleeping for $sleepTime seconds until the next check." Start-Sleep -s $sleepTime $counter += 1 } else { @@ -1202,7 +1205,7 @@ if ($PsBoundParameters.ContainsKey("startup")) { } } if ($counter -eq $retries) { - Write-PowerManagementLogMessage -Type ERROR -Message "The vCLS virtual machines did not start within the expected time. Stopping script execution..." + Write-LogMessage -Type ERROR -Message "The vCLS virtual machines did not start within the expected time. Stopping script execution..." Exit } @@ -1213,7 +1216,7 @@ if ($PsBoundParameters.ContainsKey("startup")) { # Startup the NSX Manager Nodes in the Management Workload Domain Start-CloudComponent -server $vcServer.fqdn -user $vcUser -pass $vcPass -nodes $nsxtNodes -timeout 600 if (!(Wait-ForStableNsxtClusterStatus -server $nsxtManagerFQDN -user $nsxtManagerVIP.adminUser -pass $nsxtManagerVIP.adminPassword)) { - Write-PowerManagementLogMessage -Type ERROR -Message "The NSX Manager cluster is not in 'STABLE' state. Exiting!" + Write-LogMessage -Type ERROR -Message "The NSX Manager cluster is not in 'STABLE' state. Exiting!" Exit } @@ -1221,10 +1224,10 @@ if ($PsBoundParameters.ContainsKey("startup")) { if ($nsxtEdgeNodes) { Start-CloudComponent -server $vcServer.fqdn -user $vcUser -pass $vcPass -nodes $nsxtEdgeNodes -timeout 600 } else { - Write-PowerManagementLogMessage -Type WARNING -Message "No NSX Edge nodes present. Skipping startup..." + Write-LogMessage -Type WARNING -Message "No NSX Edge nodes present. Skipping startup..." } if (-Not (Test-VCFConnection -server $server )) { - Write-PowerManagementLogMessage -Type INFO -Message "Could not connect to $server..." + Write-LogMessage -Type INFO -Message "Could not connect to $server..." } if (Test-VCFAuthentication -server $server -user $user -pass $pass) { $mgmtClusterIds = @() @@ -1238,65 +1241,65 @@ if ($PsBoundParameters.ContainsKey("startup")) { if (!$isDefault) { $answer = Read-Host -Prompt "Start up cluster $clusterName, Do you want to continue? Y/N" if ($answer -Match 'N') { - Write-PowerManagementLogMessage -Type WARNING "Cancelled start up of $clusterName. Exiting..." + Write-LogMessage -Type WARNING "Cancelled start up of $clusterName. Exiting..." Exit } else { - Write-PowerManagementLogMessage -Type INFO "Will Move Forward with start up of $clusterName" + Write-LogMessage -Type INFO "Will Move Forward with start up of $clusterName" } $esxiHosts = (Get-VCFHost | Select-Object fqdn -ExpandProperty cluster | Where-Object { $_.id -eq $clusterId.id }).fqdn foreach ($esxiNode in $esxiHosts) { if (-Not (Test-VsphereConnection -server $esxiNode)) { - Write-PowerManagementLogMessage -Type WARNING "ESXi host $esxiNode is not powered on...." + Write-LogMessage -Type WARNING "ESXi host $esxiNode is not powered on...." } else { $password = (Get-VCFCredential -resourceName $esxiNode | Select-Object password) $esxiHostPassword = $password.password[1] $status = Get-SSHEnabledStatus -server $esxiNode -user root -pass $esxiHostPassword if (-Not $status) { if (Test-vSphereAuthentication -server $esxi -user root -pass $esxiHostPassword) { - Write-PowerManagementLogMessage -Type WARNING "SSH is not enabled on $esxiNode, enabling it now..." + Write-LogMessage -Type WARNING "SSH is not enabled on $esxiNode, enabling it now..." Get-VmHostService -VMHost $esxiNode | Where-Object { $_.key -eq "TSM-SSH" } | Start-VMHostService Start-Sleep -s 10 - Write-PowerManagementLogMessage -Type INFO "Attempting to Set Maintenance Mode on $esxiNode to DISABLE" + Write-LogMessage -Type INFO "Attempting to Set Maintenance Mode on $esxiNode to DISABLE" Set-MaintenanceMode -server $esxiNode -user root -pass $esxiHostPassword -state DISABLE Start-Sleep -s 120 } else { - Write-PowerManagementLogMessage -Type ERROR "Unable to authenticate to $esxiNode. Exiting..." + Write-LogMessage -Type ERROR "Unable to authenticate to $esxiNode. Exiting..." Exit } } else { if (Test-vSphereAuthentication -server $esxi -user root -pass $esxiHostPassword) { - Write-PowerManagementLogMessage -Type INFO "Attempting to Set Maintenance Mode on $esxiNode to DISABLE" + Write-LogMessage -Type INFO "Attempting to Set Maintenance Mode on $esxiNode to DISABLE" Set-MaintenanceMode -server $esxiNode -user root -pass $esxiHostPassword -state DISABLE Start-Sleep -s 120 } else { - Write-PowerManagementLogMessage -Type ERROR "Unable to authenticate to $esxiNode. Exiting..." + Write-LogMessage -Type ERROR "Unable to authenticate to $esxiNode. Exiting..." Exit } } } } - Write-PowerManagementLogMessage -Type INFO -Message "Pausing for 30 seconds while hosts come out of maintenance mode..." + Write-LogMessage -Type INFO -Message "Pausing for 30 seconds while hosts come out of maintenance mode..." Start-Sleep -s 30 if ([float]$vcfVersion -lt [float]4.5) { # Prepare the vSAN cluster for startup - Performed on a single host only # We need some time before this step, setting hard sleep 30 sec - Write-PowerManagementLogMessage -Type INFO -Message "Pausing for 30 seconds before starting vSAN..." + Write-LogMessage -Type INFO -Message "Pausing for 30 seconds before starting vSAN..." $password = (Get-VCFCredential -resourceName $esxiHosts[0] | Select-Object password) $esxiHostPassword = $password.password[1] Invoke-EsxCommand -server $esxiHosts[0] -user root -pass $esxiHostPassword -expected "Cluster reboot/poweron is completed successfully!" -cmd "python /usr/lib/vmware/vsan/bin/reboot_helper.py recover" # We need some time before this step, setting hard sleep 30 sec - Write-PowerManagementLogMessage -Type INFO -Message "Pausing for 30 seconds before enabling vSAN updates..." + Write-LogMessage -Type INFO -Message "Pausing for 30 seconds before enabling vSAN updates..." Start-Sleep -s 30 foreach ($esxi in $esxiHosts) { $password = (Get-VCFCredential -resourceName $esxi | Select-Object password) $esxiHostPassword = $password.password[1] if (Test-vSphereAuthentication -server $esxi -user root -pass $esxiHostPassword) { - Write-PowerManagementLogMessage -Type INFO -Message "Set hosts to ignoreClusterMemberListUpdates" + Write-LogMessage -Type INFO -Message "Set hosts to ignoreClusterMemberListUpdates" Invoke-EsxCommand -server $esxi -user root -pass $esxiHostPassword -expected "Value of IgnoreClusterMemberListUpdates is 0" -cmd "esxcfg-advcfg -s 0 /VSAN/IgnoreClusterMemberListUpdates" } } - Write-PowerManagementLogMessage -Type INFO -Message "Checking vSAN status of the ESXi hosts..." + Write-LogMessage -Type INFO -Message "Checking vSAN status of the ESXi hosts..." foreach ($esxiNode in $esxiHosts) { $password = (Get-VCFCredential -resourceName $esxi | Select-Object password) $esxiHostPassword = $password.password[1] @@ -1316,24 +1319,24 @@ if ($PsBoundParameters.ContainsKey("startup")) { } # Check vSAN Status if ( (Test-VsanHealth -cluster $clusterName -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) -ne 0) { - Write-PowerManagementLogMessage -Type WARNING -Message "vSAN cluster is in an unhealthy state. Check the vSAN status in cluster '$($clusterName)'. Retry after resolving the vSAN health state. Exiting..." + Write-LogMessage -Type WARNING -Message "vSAN cluster is in an unhealthy state. Check the vSAN status in cluster '$($clusterName)'. Retry after resolving the vSAN health state. Exiting..." Exit } if ( (Test-VsanObjectResync -cluster $clusterName -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass) -ne 0) { - Write-PowerManagementLogMessage -Type ERROR -Message "vSAN object resynchronization failed. Check your environment and run the script again." + Write-LogMessage -Type ERROR -Message "vSAN object resynchronization failed. Check your environment and run the script again." Exit } # Start workflow for VCF prior version 4.5 # Start vSphere HA if (!$(Set-VsphereHA -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass -cluster $clusterName -enableHA)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to enable vSphere High Availability for cluster '$cluster'. Exiting..." + Write-LogMessage -Type ERROR -Message "Unable to enable vSphere High Availability for cluster '$cluster'. Exiting..." Exit } # Restore the DRS Automation Level to the mode backed up for Management Domain Cluster during shutdown if ([string]::IsNullOrEmpty($drsAutomationLevel)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to enable Drs Automation Level for cluster '$cluster'. Exiting..." + Write-LogMessage -Type ERROR -Message "Unable to enable Drs Automation Level for cluster '$cluster'. Exiting..." Exit } else { Set-DrsAutomationLevel -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass -cluster $clusterName -level $drsAutomationLevel @@ -1348,7 +1351,7 @@ if ($PsBoundParameters.ContainsKey("startup")) { while ($counter -ne $retries) { $powerOnVMcount = (Get-VMsWithPowerStatus -powerstate "poweredon" -server $vcfVcenterDetails.fqdn -user $vcfVcenterDetails.ssoAdmin -pass $vcfVcenterDetails.ssoAdminPass -pattern "(^vCLS-\w{8}-\w{4}-\w{4}-\w{4}-\w{12})|(^vCLS\s*\(\d+\))|(^vCLS\s*$)" -silence).count if ( $powerOnVMcount -lt 3 ) { - Write-PowerManagementLogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS virtual machines startup will take some time. Please wait..." + Write-LogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS virtual machines startup will take some time. Please wait..." Start-Sleep -s $sleepTime $counter += 1 } else { @@ -1356,7 +1359,7 @@ if ($PsBoundParameters.ContainsKey("startup")) { } } if ($counter -eq $retries) { - Write-PowerManagementLogMessage -Type ERROR -Message "vCLS virtual machines did not start within the expected time. Exiting..." + Write-LogMessage -Type ERROR -Message "vCLS virtual machines did not start within the expected time. Exiting..." Exit } } @@ -1366,24 +1369,56 @@ if ($PsBoundParameters.ContainsKey("startup")) { } } - Write-PowerManagementLogMessage -Type INFO -Message "##################################################################################" + Write-LogMessage -Type INFO -Message "##################################################################################" + if ([float]$vcfVersion -lt [float]4.5) { + Write-LogMessage -Type INFO -Message "vSphere vSphere High Availability has been enabled by the script. Please disable it according to your environment's design." + } + Write-LogMessage -Type INFO -Message "Check your environment and start any additional virtual machines that you host in the management domain." + Write-LogMessage -Type INFO -Message "Use the following command to automatically start VMs" + Write-LogMessage -Type INFO -Message "Start-CloudComponent -server $($vcServer.fqdn) -user $vcUser -pass $vcPass -nodes -timeout 600" if ([float]$vcfVersion -lt [float]4.5) { - Write-PowerManagementLogMessage -Type INFO -Message "vSphere vSphere High Availability has been enabled by the script. Please disable it according to your environment's design." + Write-LogMessage -Type WARNING -Message "If you have enabled SSH for the ESXi hosts in management domain, disable it at this point." + Write-LogMessage -Type INFO -Message "If you have enabled SSH for the ESXi hosts in management domain, disable it at this point." + } + if ([float]$vcfVersion -gt [float]4.4) { + Write-LogMessage -Type WARNING -Message "If you have disabled lockdown mode for the ESXi hosts in management domain, enable it back at this point." + Write-LogMessage -Type INFO -Message "If you have disabled lockdown mode for the ESXi hosts in management domain, enable it back at this point." } - Write-PowerManagementLogMessage -Type INFO -Message "Check your environment and start any additional virtual machines that you host in the management domain." - Write-PowerManagementLogMessage -Type INFO -Message "Use the following command to automatically start VMs" - Write-PowerManagementLogMessage -Type INFO -Message "Start-CloudComponent -server $($vcServer.fqdn) -user $vcUser -pass $vcPass -nodes -timeout 600" + Write-LogMessage -Type INFO -Message "##################################################################################" + Write-LogMessage -Type INFO -Message "End of the startup sequence!" + Write-LogMessage -Type INFO -Message "##################################################################################" + } Catch { + Write-DebugMessage -object $_ + Exit + } +} + Write-LogMessage -Type INFO -Message "Start-CloudComponent -server $($vcServer.fqdn) -user $vcUser -pass $vcPass -nodes -timeout 600" + if ([float]$vcfVersion -lt [float]4.5) { + Write-LogMessage -Type INFO -Message "If you have enabled SSH for the ESXi hosts in management domain, disable it at this point." + } + if ([float]$vcfVersion -gt [float]4.4) { + Write-LogMessage -Type INFO -Message "If you have disabled lockdown mode for the ESXi hosts in management domain, enable it back at this point." + } + Write-LogMessage -Type INFO -Message "##################################################################################" + Write-LogMessage -Type INFO -Message "End of the startup sequence!" + Write-LogMessage -Type INFO -Message "##################################################################################" + } Catch { + Write-DebugMessage -object $_ + Exit + } +} + Write-LogMessage -Type INFO -Message "Start-CloudComponent -server $($vcServer.fqdn) -user $vcUser -pass $vcPass -nodes -timeout 600" if ([float]$vcfVersion -lt [float]4.5) { - Write-PowerManagementLogMessage -Type WARNING -Message "If you have enabled SSH for the ESXi hosts in management domain, disable it at this point." + Write-LogMessage -Type INFO -Message "If you have enabled SSH for the ESXi hosts in management domain, disable it at this point." } if ([float]$vcfVersion -gt [float]4.4) { - Write-PowerManagementLogMessage -Type WARNING -Message "If you have disabled lockdown mode for the ESXi hosts in management domain, enable it back at this point." + Write-LogMessage -Type INFO -Message "If you have disabled lockdown mode for the ESXi hosts in management domain, enable it back at this point." } - Write-PowerManagementLogMessage -Type INFO -Message "##################################################################################" - Write-PowerManagementLogMessage -Type INFO -Message "End of the startup sequence!" - Write-PowerManagementLogMessage -Type INFO -Message "##################################################################################" + Write-LogMessage -Type INFO -Message "##################################################################################" + Write-LogMessage -Type INFO -Message "End of the startup sequence!" + Write-LogMessage -Type INFO -Message "##################################################################################" } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ Exit } } diff --git a/SampleScripts/PowerManagement-WorkloadDomain.ps1 b/SampleScripts/PowerManagement-WorkloadDomain.ps1 index b24c34c..ea532d1 100644 --- a/SampleScripts/PowerManagement-WorkloadDomain.ps1 +++ b/SampleScripts/PowerManagement-WorkloadDomain.ps1 @@ -68,13 +68,73 @@ Function Get-Password { return $password } +Function Write-LogMessage { + Param ( + [Parameter (Mandatory = $true)] [AllowEmptyString()] [String]$Message, + [Parameter (Mandatory = $false)] [ValidateSet("INFO", "ERROR", "WARNING", "EXCEPTION")] [String]$Type, + [Parameter (Mandatory = $false)] [String]$Colour, + [Parameter (Mandatory = $false)] [String]$SkipnewLine + ) + + $ErrorActionPreference = 'Stop' + + if (!$colour) { + switch ($type) { + "INFO" { + $colour = "Green" + } + "WARNING" { + $colour = "Yellow" + } + "ERROR" { + $colour = "Red" + } + "EXCEPTION" { + $colour = "Magenta" + } + default { + $colour = "White" + } + } + } + + $timeStamp = Get-Date -Format "MM-dd-yyyy_HH:mm:ss" + + Write-Host -NoNewline -ForegroundColor White " [$timeStamp]" + if ($skipNewLine) { + Write-Host -NoNewline -ForegroundColor $colour " $type $message" + } else { + Write-Host -ForegroundColor $colour " $type $message" + } + $logContent = '[' + $timeStamp + '] ' + $type + ' ' + $message + if ($type -match "ERROR") { + Write-Error -Message $Message + } +} + +Function Write-DebugMessage { + Param ( + [Parameter (Mandatory = $true)] [PSObject]$object + ) + + $ErrorActionPreference = 'Stop' + + $lineNumber = $object.InvocationInfo.ScriptLineNumber + $lineText = $object.InvocationInfo.Line.trim() + $errorMessage = $object.Exception.Message + Write-LogMessage -Message " ERROR at Script Line $lineNumber" -Colour Red + Write-LogMessage -Message " Relevant Command: $lineText" -Colour Red + Write-LogMessage -Message " ERROR Message: $errorMessage" -Colour Red + Write-Error -Message $errorMessage +} + #EndRegion Non Exported Functions ###### ########################################################################## $pass = Get-Password -User $user -Password $pass # Error Handling (script scope function) -Function Debug-CatchWriterForPowerManagement { +Function Write-DebugMessage { Param ( [Parameter (Mandatory = $true)] [PSObject]$object ) @@ -82,9 +142,9 @@ Function Debug-CatchWriterForPowerManagement { $lineNumber = $object.InvocationInfo.ScriptLineNumber $lineText = $object.InvocationInfo.Line.trim() $errorMessage = $object.Exception.Message - Write-PowerManagementLogMessage -message " ERROR at Script Line $lineNumber" - Write-PowerManagementLogMessage -message " Relevant Command: $lineText" - Write-PowerManagementLogMessage -message " ERROR Message: $errorMessage" + Write-LogMessage -message " ERROR at Script Line $lineNumber" + Write-LogMessage -message " Relevant Command: $lineText" + Write-LogMessage -message " ERROR Message: $errorMessage" Write-Error -Message $errorMessage } @@ -97,7 +157,7 @@ Try { else { $customerVmMessage = "Process WILL NOT gracefully shutdown customer deployed Virtual Machines not managed by VCF, if deployed within the Workload Domain." } } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } # Pre-Checks @@ -109,34 +169,34 @@ Try { if ($PsBoundParameters.ContainsKey("startup")) { $str2 = $str2 + " -startup" } if ($PsBoundParameters.ContainsKey("shutdown")) { $str2 = $str2 + " -shutdown" } if ($PsBoundParameters.ContainsKey("shutdownCustomerVm")) { $str2 = $str2 + " -shutdownCustomerVm" } - Write-PowerManagementLogMessage -Type INFO -Message "Script used: $str1" - Write-PowerManagementLogMessage -Type INFO -Message "Script syntax: $str2" - Write-PowerManagementLogMessage -Type INFO -Message "Setting up the log file to path $logfile" - if (-Not $null -eq $customerVmMessage) { Write-PowerManagementLogMessage -Type INFO -Message $customerVmMessage } + Write-LogMessage -Type INFO -Message "Script used: $str1" + Write-LogMessage -Type INFO -Message "Script syntax: $str2" + Write-LogMessage -Type INFO -Message "Setting up the log file to path $logfile" + if (-Not $null -eq $customerVmMessage) { Write-LogMessage -Type INFO -Message $customerVmMessage } if (!(Test-EndpointConnection -server $server -Port 443)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot communicate with SDDC Manager ($server). Check the FQDN or IP address or power state of the '$server'." + Write-LogMessage -Type ERROR -Message "Cannot communicate with SDDC Manager ($server). Check the FQDN or IP address or power state of the '$server'." Exit } else { $statusMsg = Request-VCFToken -fqdn $server -username $user -password $pass -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ( $statusMsg ) { Write-PowerManagementLogMessage -Type INFO -Message $statusMsg } - if ( $warnMsg ) { Write-PowerManagementLogMessage -Type WARNING -Message $warnMsg } - if ( $ErrorMsg ) { Write-PowerManagementLogMessage -Type ERROR -Message $ErrorMsg } + if ( $statusMsg ) { Write-LogMessage -Type INFO -Message $statusMsg } + if ( $warnMsg ) { Write-LogMessage -Type WARNING -Message $warnMsg } + if ( $ErrorMsg ) { Write-LogMessage -Type ERROR -Message $ErrorMsg } if ($accessToken) { - Write-PowerManagementLogMessage -Type INFO -Message "Connection to SDDC Manager has been validated successfully." + Write-LogMessage -Type INFO -Message "Connection to SDDC Manager has been validated successfully." } } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } # Gather details from SDDC Manager Try { - Write-PowerManagementLogMessage -Type INFO -Message "Attempting to connect to VMware Cloud Foundation to gather system details..." + Write-LogMessage -Type INFO -Message "Attempting to connect to VMware Cloud Foundation to gather system details..." $statusMsg = Request-VCFToken -fqdn $server -username $user -password $pass -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ($statusMsg) { Write-PowerManagementLogMessage -Type INFO -Message $statusMsg } if ($warnMsg) { Write-PowerManagementLogMessage -Type WARNING -Message $warnMsg } if ($ErrorMsg) { Write-PowerManagementLogMessage -Type ERROR -Message $ErrorMsg } + if ($statusMsg) { Write-LogMessage -Type INFO -Message $statusMsg } if ($warnMsg) { Write-LogMessage -Type WARNING -Message $warnMsg } if ($ErrorMsg) { Write-LogMessage -Type ERROR -Message $ErrorMsg } if ($accessToken) { - Write-PowerManagementLogMessage -Type INFO -Message "Gathering system details from the SDDC Manager inventory... It will take some time." + Write-LogMessage -Type INFO -Message "Gathering system details from the SDDC Manager inventory... It will take some time." # Gather Details from SDDC Manager $managementDomain = Get-VCFWorkloadDomain | Where-Object { $_.type -eq "MANAGEMENT" } @@ -144,7 +204,7 @@ Try { $allWld = Get-VCFWorkloadDomain | Where-Object { ($_.Type -ne "MANAGEMENT") } $allWldVCs = $allWld.vcenters.fqdn if ([string]::IsNullOrEmpty($workloadDomain)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Domain $sddcDomain doesn't exist. Check your environment and try again. " + Write-LogMessage -Type ERROR -Message "Domain $sddcDomain doesn't exist. Check your environment and try again. " Exit } # Check if there are multiple clusters in the WLD @@ -166,7 +226,7 @@ Try { if ($workloadDomain.clusters.id.count -gt 1) { - Write-PowerManagementLogMessage -Type INFO -Message "There are multiple clusters in VI domain '$sddcDomain'." + Write-LogMessage -Type INFO -Message "There are multiple clusters in VI domain '$sddcDomain'." } foreach ($id in $($workloadDomain.clusters.id)) { $clusterData = (Get-VCFCluster | Where-Object { $_.id -eq ($id) }) @@ -175,7 +235,7 @@ Try { $sddcClusterArray += $clusterData.name $esxiWorkloadCluster[$clusterData.name] = @() } - Write-PowerManagementLogMessage -Type INFO -Message "Clusters in SDDC Manager database: $($sddcClusterArray -join ",")" + Write-LogMessage -Type INFO -Message "Clusters in SDDC Manager database: $($sddcClusterArray -join ",")" if ($vsanCluster) { foreach ($name in $userClusterArray) { @@ -186,18 +246,18 @@ Try { } $clusterDetails = $userClusterDetails if (($userClusterDetails.count -eq $sddcClusterDetails.count) -and (((Compare-Object $userClusterDetails $sddcClusterDetails -IncludeEqual | Where-Object -FilterScript { $_.SideIndicator -eq '==' }).InputObject).count -eq $sddcClusterDetails.count)) { - Write-PowerManagementLogMessage -Type INFO -Message "All cluster-related information is correct." + Write-LogMessage -Type INFO -Message "All cluster-related information is correct." $allClusterShutdown = $true } if (((Compare-Object $sddcClusterArray $userClusterArray -IncludeEqual | Where-Object -FilterScript { $_.SideIndicator -eq '=>' }).InputObject).count) { $wrongClusterNames = (Compare-Object $sddcClusterArray $userClusterArray -IncludeEqual | Where-Object -FilterScript { $_.SideIndicator -eq '=>' }).InputObject - Write-PowerManagementLogMessage -Type WARNING -Message "A wrong cluster name has been passed." - Write-PowerManagementLogMessage -Type WARNING -Message "The known clusters, part of this workload domain are:$($sddcClusterDetails.name)" - Write-PowerManagementLogMessage -Type WARNING -Message "The cluster names passed are: $userClusterArray" - Write-PowerManagementLogMessage -Type WARNING -Message "Clusters not matching the SDDC Manager database: $wrongClusterNames" - Write-PowerManagementLogMessage -Type ERROR -Message "Please cross check and run the script again. Exiting!" + Write-LogMessage -Type WARNING -Message "A wrong cluster name has been passed." + Write-LogMessage -Type WARNING -Message "The known clusters, part of this workload domain are:$($sddcClusterDetails.name)" + Write-LogMessage -Type WARNING -Message "The cluster names passed are: $userClusterArray" + Write-LogMessage -Type WARNING -Message "Clusters not matching the SDDC Manager database: $wrongClusterNames" + Write-LogMessage -Type ERROR -Message "Please cross check and run the script again. Exiting!" } - Write-PowerManagementLogMessage -Type INFO -Message "All clusters to be taken care of: '$allClusterShutdown'" + Write-LogMessage -Type INFO -Message "All clusters to be taken care of: '$allClusterShutdown'" } else { foreach ($id in $($workloadDomain.clusters.id)) { $clusterData = (Get-VCFCluster | Where-Object { $_.id -eq ($id) }) @@ -243,14 +303,14 @@ Try { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue | Out-Null } if (Test-EndpointConnection -server $vcServer.fqdn -port 443 ) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$($vcServer.fqdn)' ..." + Write-LogMessage -Type INFO -Message "Connecting to '$($vcServer.fqdn)' ..." Connect-VIServer -Server $vcServer.fqdn -Protocol https -User $vcUser -Password $vcPass -ErrorVariable $vcConnectError | Out-Null if ($DefaultVIServer.Name -eq $vcServer.fqdn) { $vxrailVMObject = Get-VM | Where-Object { $_.Guest.Hostname -Match $vxRailCred.resource.resourceName -Or $_.Guest.Hostname -Match ($vxRailCred.resource.resourceName.Split("."))[0] } if ($vxrailVMObject) { $vxRailVmName = $vxrailVMObject.Name } else { - Write-PowerManagementLogMessage -Type ERROR -Message "VxRail($($vxRailCred.resource.resourceName)) Virtual Machine object cannot be located within VC Server ($($vcServer.fqdn))" + Write-LogMessage -Type ERROR -Message "VxRail($($vxRailCred.resource.resourceName)) Virtual Machine object cannot be located within VC Server ($($vcServer.fqdn))" } } } @@ -261,7 +321,7 @@ Try { $vxRailDetails | Add-Member -Type NoteProperty -Name username -Value $vxRailCred.username $vxRailDetails | Add-Member -Type NoteProperty -Name password -Value $vxRailCred.password [Array]$vcfVMs += ($vxRailDetails.vmName) - Write-PowerManagementLogMessage -Type INFO -Message "VxRail Manager($vxRailVmName) found within VC Server ($($vcServer.fqdn))" + Write-LogMessage -Type INFO -Message "VxRail Manager($vxRailVmName) found within VC Server ($($vcServer.fqdn))" } else { $vxRailDetails = "" } @@ -295,10 +355,10 @@ Try { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue | Out-Null } if ( Test-EndpointConnection -server $vcServer.fqdn -port 443 ) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$($vcServer.fqdn)' ..." + Write-LogMessage -Type INFO -Message "Connecting to '$($vcServer.fqdn)' ..." Connect-VIServer -Server $vcServer.fqdn -Protocol https -User $vcUser -Password $vcPass -ErrorVariable $vcConnectError | Out-Null if ($DefaultVIServer.Name -eq $vcServer.fqdn) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$($vcServer.fqdn)' and trying to get host status..." + Write-LogMessage -Type INFO -Message "Connected to server '$($vcServer.fqdn)' and trying to get host status..." $HostsInMaintenanaceOrDisconnectedState = Get-VMHost $hostsName | Where-Object { ($_.ConnectionState -eq 'Maintenance') -or ($_.ConnectionState -eq 'NotResponding') -or ($_.ConnectionState -eq 'Disconnected') } if ( $HostsInMaintenanaceOrDisconnectedState.count -eq $sddcHostsClusterMapping[$clusterName].count) { $ClusterStatusMapping[$clusterName] = 'DOWN' @@ -306,21 +366,21 @@ Try { $ClusterStatusMapping[$clusterName] = 'UP' } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$($vcServer.fqdn)' has failed. Check the console output for more details." + Write-LogMessage -Type ERROR -Message "Connection to '$($vcServer.fqdn)' has failed. Check the console output for more details." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$($vcServer.fqdn)' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$($vcServer.fqdn)' has failed. Check your environment and try again" } } } # We will get NSX-T details in the respective startup/shutdown sections below. } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to vCenter Server ($($vcServer.fqdn)). Check your credentials." + Write-LogMessage -Type ERROR -Message "Cannot connect to vCenter Server ($($vcServer.fqdn)). Check your credentials." Exit } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } # Run the Shutdown procedures @@ -340,13 +400,13 @@ Try { [Array]$vcfVMs += $node.Split(".")[0] } - Write-PowerManagementLogMessage -Type INFO -Message "Trying to fetch information about all powered-on vCLS virtual machines from vCenter Server $($vcServer.fqdn)..." + Write-LogMessage -Type INFO -Message "Trying to fetch information about all powered-on vCLS virtual machines from vCenter Server $($vcServer.fqdn)..." [Array]$vclsVMs += Get-VMsWithPowerStatus -server $vcServer.fqdn -user $vcUser -pass $vcPass -powerstate "poweredon"-pattern "(^vCLS-\w{8}-\w{4}-\w{4}-\w{4}-\w{12})|(^vCLS\s*\(\d+\))|(^vCLS\s*$)" -silence foreach ($vm in $vclsVMs) { [Array]$vcfVMs += $vm } - Write-PowerManagementLogMessage -Type INFO -Message "Fetching all powered on vSAN File Services virtual machines from vCenter Server instance $($vcenter)..." + Write-LogMessage -Type INFO -Message "Fetching all powered on vSAN File Services virtual machines from vCenter Server instance $($vcenter)..." [Array]$vsanFsVMs += Get-VMsWithPowerStatus -powerstate "poweredon" -server $vcServer.fqdn -user $vcUser -pass $vcPass -pattern "(vSAN File)" -silence foreach ($vm in $vsanFsVMs) { [Array]$vcfVMs += $vm @@ -365,8 +425,8 @@ Try { $nsxtClusterEdgeNodes = @() if ($statusOfNsxtClusterVMs -ne 'running') { - Write-PowerManagementLogMessage -Type WARNING -Message "The NSX Manager VMs have been stopped. The NSX Edge VMs will not be handled in an automatic way." - Write-PowerManagementLogMessage -Type WARNING -Message "The NSX Manager VMs have been stopped. We could not check if this NSX Manager is spanned across Workload Domains." + Write-LogMessage -Type WARNING -Message "The NSX Manager VMs have been stopped. The NSX Edge VMs will not be handled in an automatic way." + Write-LogMessage -Type WARNING -Message "The NSX Manager VMs have been stopped. We could not check if this NSX Manager is spanned across Workload Domains." } else { Try { [Array]$nsxtEdgeNodes = Get-EdgeNodeFromNSXManager -server $nsxtManagerFQDN -user $nsxtManagerVIP.adminUser -pass $nsxtManagerVIP.adminPassword -VCfqdn $vcServer.fqdn @@ -374,7 +434,7 @@ Try { [Array]$vcfVMs += $node } } Catch { - Write-PowerManagementLogMessage -Type ERROR -Message "Something went wrong! Unable to fetch NSX Edge node information from NSX Manager '$nsxtManagerFQDN'. Exiting!" + Write-LogMessage -Type ERROR -Message "Something went wrong! Unable to fetch NSX Edge node information from NSX Manager '$nsxtManagerFQDN'. Exiting!" } # This variable holds True of False based on if NSX is spanned across workloads or not. @@ -400,15 +460,15 @@ Try { } if (($DownCount -eq ($count - 1)) -or ($DownCount -eq $count) ) { $lastElement = $true - Write-PowerManagementLogMessage -Type INFO -Message "Last cluster of VSAN detected" + Write-LogMessage -Type INFO -Message "Last cluster of VSAN detected" } if ($ClusterStatusMapping[$cluster.name] -eq 'DOWN') { - Write-PowerManagementLogMessage -Type INFO -Message "Cluster '$($cluster.name)' is already stopped, hence proceeding with next cluster in the sequence" + Write-LogMessage -Type INFO -Message "Cluster '$($cluster.name)' is already stopped, hence proceeding with next cluster in the sequence" Continue } - Write-PowerManagementLogMessage -Type INFO -Message "Processing cluster '$($cluster.name)'..." + Write-LogMessage -Type INFO -Message "Processing cluster '$($cluster.name)'..." $esxiDetails = $esxiWorkloadCluster[$cluster.name] @@ -422,22 +482,22 @@ Try { if (Test-VsphereConnection -server $esxiNode) { $status = Get-SSHEnabledStatus -server $esxiNode.fqdn -user $esxiNode.username -pass $esxiNode.password if (-Not $status) { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to establish an SSH connection to ESXi host $($esxiNode.fqdn). SSH is not enabled. Exiting..." + Write-LogMessage -Type ERROR -Message "Unable to establish an SSH connection to ESXi host $($esxiNode.fqdn). SSH is not enabled. Exiting..." Exit } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to connect to ESXi host $($esxiNode.fqdn). Exiting..." + Write-LogMessage -Type ERROR -Message "Unable to connect to ESXi host $($esxiNode.fqdn). Exiting..." Exit } } } Catch { - Write-PowerManagementLogMessage -Type ERROR -Message $_.Exception.Message + Write-LogMessage -Type ERROR -Message $_.Exception.Message Exit } } else { foreach ($esxiNode in $esxiDetails) { if (!(Test-EndpointConnection -server $esxiNode.fqdn -port 443)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to communicate with ESXi host $($esxiNode.fqdn). Check the FQDN or IP address, or the power state. Exiting..." + Write-LogMessage -Type ERROR -Message "Unable to communicate with ESXi host $($esxiNode.fqdn). Check the FQDN or IP address, or the power state. Exiting..." Exit } } @@ -447,16 +507,16 @@ Try { # Check if Tanzu is enabled in WLD $status = Get-TanzuEnabledClusterStatus -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name if ($status -eq $True) { - Write-PowerManagementLogMessage -Type ERROR -Message "Currently workload domains with vSphere with Tanzu are not supported. Exiting..." + Write-LogMessage -Type ERROR -Message "Currently workload domains with vSphere with Tanzu are not supported. Exiting..." Exit } $clusterVcfVMs = @() $clusterVclsVMs = @() # TODO If not specific cluster is passed - we should check for customer VMs in all clusters. In this way we will fail early if there are some VMs running and not managed by VCF. - Write-PowerManagementLogMessage -Type INFO -Message "Trying to fetch information about all powered-on virtual machines for the specified vSphere cluster $($cluster.name)..." + Write-LogMessage -Type INFO -Message "Trying to fetch information about all powered-on virtual machines for the specified vSphere cluster $($cluster.name)..." [Array]$clusterAllVMs = Get-VMToClusterMapping -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -folder "VM" -powerstate "poweredon" - Write-PowerManagementLogMessage -Type INFO -Message "Trying to fetch information about all powered-on vCLS virtual machines for a the specified vSphere cluster $($cluster.name)..." + Write-LogMessage -Type INFO -Message "Trying to fetch information about all powered-on vCLS virtual machines for a the specified vSphere cluster $($cluster.name)..." [Array]$clusterVclsVMs = Get-VMToClusterMapping -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -folder "vcls" -powerstate "poweredon" foreach ($vm in $clusterVclsVMs) { [Array]$clusterVcfVMs += $vm @@ -474,13 +534,13 @@ Try { } } } - Write-PowerManagementLogMessage -Type INFO -Message "Trying to fetch information about all powered-on customer virtual machines for the specified vSphere cluster $($cluster.name)..." + Write-LogMessage -Type INFO -Message "Trying to fetch information about all powered-on customer virtual machines for the specified vSphere cluster $($cluster.name)..." $clusterCustomerVMs = $clusterAllVMs | Where-Object { $vcfVMs -NotContains $_ } $clusterVcfVMs_string = $clusterVcfVMs -join "; " - Write-PowerManagementLogMessage -Type INFO -Message "Management virtual machines covered by the script for the cluster $($cluster.name): '$($clusterVcfVMs_string)' ." + Write-LogMessage -Type INFO -Message "Management virtual machines covered by the script for the cluster $($cluster.name): '$($clusterVcfVMs_string)' ." if ($clusterCustomerVMs.count -ne 0) { $clusterCustomerVMs_string = $clusterCustomerVMs -join "; " - Write-PowerManagementLogMessage -Type INFO -Message "Virtual machines for the cluster $($cluster.name) that are not covered by the script: '$($clusterCustomerVMs_string)'. These VMs will be stopped in a random order if the 'shutdownCustomerVm' flag is passed." + Write-LogMessage -Type INFO -Message "Virtual machines for the cluster $($cluster.name) that are not covered by the script: '$($clusterCustomerVMs_string)'. These VMs will be stopped in a random order if the 'shutdownCustomerVm' flag is passed." } # Check if VMware Tools are running in the customer VMs - if not we could not stop them gracefully @@ -491,12 +551,12 @@ Try { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue | Out-Null } if ( Test-EndpointConnection -server $vcServer.fqdn -port 443 ) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$($vcServer.fqdn)' ..." + Write-LogMessage -Type INFO -Message "Connecting to '$($vcServer.fqdn)' ..." Connect-VIServer -Server $vcServer.fqdn -Protocol https -User $vcUser -Password $vcPass -ErrorVariable $vcConnectError | Out-Null if ($DefaultVIServer.Name -eq $vcServer.fqdn) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$($vcServer.fqdn)' and trying to get VMware Tools status." + Write-LogMessage -Type INFO -Message "Connected to server '$($vcServer.fqdn)' and trying to get VMware Tools status." foreach ($vm in $clusterCustomerVMs) { - Write-PowerManagementLogMessage -Type INFO -Message "Checking VMware Tools status for '$vm'..." + Write-LogMessage -Type INFO -Message "Checking VMware Tools status for '$vm'..." $vm_data = Get-VM -Name $vm if ($vm_data.ExtensionData.Guest.ToolsRunningStatus -eq "guestToolsRunning") { [Array]$VMwareToolsRunningVMs += $vm @@ -505,7 +565,7 @@ Try { } } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot to connect to vCenter Server '$($vcServer.fqdn)'. The command returned the following error: '$vcConnectError'." + Write-LogMessage -Type ERROR -Message "Cannot to connect to vCenter Server '$($vcServer.fqdn)'. The command returned the following error: '$vcConnectError'." } } # Disconnect from the VC @@ -514,8 +574,8 @@ Try { } if ($VMwareToolsNotRunningVMs.count -ne 0) { $noToolsVMs = $VMwareToolsNotRunningVMs -join "; " - Write-PowerManagementLogMessage -Type WARNING -Message "There are some VMs that are not managed by VMware Cloud Foundation where VMware Tools isn't running. Unable to shut down these VMs:'$noToolsVMs'." - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot proceed until these VMs are shut down manually. Shut them down manually and run the script again." + Write-LogMessage -Type WARNING -Message "There are some VMs that are not managed by VMware Cloud Foundation where VMware Tools isn't running. Unable to shut down these VMs:'$noToolsVMs'." + Write-LogMessage -Type ERROR -Message "Cannot proceed until these VMs are shut down manually. Shut them down manually and run the script again." Exit } } @@ -523,15 +583,15 @@ Try { if ($clusterCustomerVMs.count -ne 0) { $clusterCustomerVMs_string = $clusterCustomerVMs -join "; " if ($PsBoundParameters.ContainsKey("shutdownCustomerVm")) { - Write-PowerManagementLogMessage -Type WARNING -Message "Some VMs are still powered on. -shutdownCustomerVm is passed to the script." - Write-PowerManagementLogMessage -Type WARNING -Message "Hence shutting down VMs not managed by SDDC Manager to put the host in maintenance mode." - Write-PowerManagementLogMessage -Type WARNING -Message "The list of Non VCF management VMs: '$clusterCustomerVMs_string'." + Write-LogMessage -Type WARNING -Message "Some VMs are still powered on. -shutdownCustomerVm is passed to the script." + Write-LogMessage -Type WARNING -Message "Hence shutting down VMs not managed by SDDC Manager to put the host in maintenance mode." + Write-LogMessage -Type WARNING -Message "The list of Non VCF management VMs: '$clusterCustomerVMs_string'." # Stop Customer VMs with one call to VC: Stop-CloudComponent -server $vcServer.fqdn -user $vcUser -pass $vcPass -nodes $clusterCustomerVMs -timeout 300 } else { - Write-PowerManagementLogMessage -Type WARNING -Message "Some VMs are still powered on. -shutdownCustomerVm is not passed to the script." - Write-PowerManagementLogMessage -Type WARNING -Message "Hence not shutting down VMs that are not managed by VMware Cloud Foundation: '$clusterCustomerVMs_string'." - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot proceed until these VMs are shut down manually or the customer VM Shutdown option is set to true. Please take the necessary action and run the script again." + Write-LogMessage -Type WARNING -Message "Some VMs are still powered on. -shutdownCustomerVm is not passed to the script." + Write-LogMessage -Type WARNING -Message "Hence not shutting down VMs that are not managed by VMware Cloud Foundation: '$clusterCustomerVMs_string'." + Write-LogMessage -Type ERROR -Message "Cannot proceed until these VMs are shut down manually or the customer VM Shutdown option is set to true. Please take the necessary action and run the script again." Exit } } @@ -541,10 +601,10 @@ Try { if ($nsxtClusterEdgeNodes) { Stop-CloudComponent -server $vcServer.fqdn -user $vcUser -pass $vcPass -nodes $nsxtClusterEdgeNodes -timeout 600 } else { - Write-PowerManagementLogMessage -Type WARNING -Message "No NSX Edge nodes found for a given cluster '$($cluster.name)' . Skipping edge nodes shutdown..." + Write-LogMessage -Type WARNING -Message "No NSX Edge nodes found for a given cluster '$($cluster.name)' . Skipping edge nodes shutdown..." } } else { - Write-PowerManagementLogMessage -Type WARNING -Message "'$($vcServer.fqdn)' might already be shut down. Skipping shutdown of $nsxtEdgeNodes..." + Write-LogMessage -Type WARNING -Message "'$($vcServer.fqdn)' might already be shut down. Skipping shutdown of $nsxtEdgeNodes..." } @@ -566,7 +626,7 @@ Try { } } if (-not $allOtherVcDown) { - Write-PowerManagementLogMessage -Type WARNING -Message "NSX Manager is shared across workload domains. Some of the vCenter Server instances for these workload domains are still running. Hence, not shutting down NSX Manager at this point." + Write-LogMessage -Type WARNING -Message "NSX Manager is shared across workload domains. Some of the vCenter Server instances for these workload domains are still running. Hence, not shutting down NSX Manager at this point." } else { if ($lastElement) { Stop-CloudComponent -server $mgmtVcServer.fqdn -user $mgmtVcUser -pass $mgmtVcPass -nodes $nsxtNodes -timeout 600 @@ -584,18 +644,18 @@ Try { if (Test-EndpointConnection -server $vcServer.fqdn -port 443) { Set-Retreatmode -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -mode enable } else { - Write-PowerManagementLogMessage -Type WARNING -Message "'$($vcServer.fqdn)' might already be shut down. Skipping putting the cluster in retreat mode..." + Write-LogMessage -Type WARNING -Message "'$($vcServer.fqdn)' might already be shut down. Skipping putting the cluster in retreat mode..." } # Waiting for vCLS VMs to be stopped for ($retries*10) seconds - Write-PowerManagementLogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS shutdown will take some time, please wait..." + Write-LogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS shutdown will take some time, please wait..." $counter = 0 $retries = 10 $sleepTime = 30 while ($counter -ne $retries) { $powerOnVMcount = (Get-VMToClusterMapping -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -folder "vcls" -powerstate "poweredon" -silence).count if ( $powerOnVMcount ) { - Write-PowerManagementLogMessage -Type INFO -Message "Some vCLS VMs are still running. Sleeping for $sleepTime seconds until next check..." + Write-LogMessage -Type INFO -Message "Some vCLS VMs are still running. Sleeping for $sleepTime seconds until next check..." Start-Sleep -s $sleepTime $counter += 1 } else { @@ -603,7 +663,7 @@ Try { } } if ($counter -eq $retries) { - Write-PowerManagementLogMessage -Type ERROR -Message "The vCLS VMs were not shut down within the expected time. Stopping the script execution." + Write-LogMessage -Type ERROR -Message "The vCLS VMs were not shut down within the expected time. Stopping the script execution." Exit } @@ -613,27 +673,27 @@ Try { $RemoteVMs = @() $RemoteVMs = Get-poweronVMsOnRemoteDS -server $vcServer.fqdn -user $vcUser -pass $vcPass -clustertocheck $cluster.name if ($RemoteVMs.count -eq 0) { - Write-PowerManagementLogMessage -Type INFO -Message "All remote VMs are powered off." + Write-LogMessage -Type INFO -Message "All remote VMs are powered off." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Not all remote VMs are powered off : $($RemoteVMs.Name), Unable to proceed. Please stop the VMs running on vSAN HCI Mesh datastore shared by this cluster." + Write-LogMessage -Type ERROR -Message "Not all remote VMs are powered off : $($RemoteVMs.Name), Unable to proceed. Please stop the VMs running on vSAN HCI Mesh datastore shared by this cluster." } } if ( (Test-VsanHealth -cluster $cluster.name -server $vcServer.fqdn -user $vcUser -pass $vcPass) -eq 0) { - Write-PowerManagementLogMessage -Type INFO -Message "vSAN health is good." + Write-LogMessage -Type INFO -Message "vSAN health is good." } else { - Write-PowerManagementLogMessage -Type WARNING -Message "The vSAN cluster isn't in a healthy state. Check the vSAN health status in vCenter Server '$($vcServer.fqdn)'. After vSAN health is restored, run the script again." - Write-PowerManagementLogMessage -Type WARNING -Message "If the script execution has reached ESXi vSAN shutdown previously, this warning is expected. Please continue by following the documentation of VMware Cloud Foundation. " - Write-PowerManagementLogMessage -Type ERROR -Message "The vSAN cluster isn't in a healthy state. Check the messages above for a solution." + Write-LogMessage -Type WARNING -Message "The vSAN cluster isn't in a healthy state. Check the vSAN health status in vCenter Server '$($vcServer.fqdn)'. After vSAN health is restored, run the script again." + Write-LogMessage -Type WARNING -Message "If the script execution has reached ESXi vSAN shutdown previously, this warning is expected. Please continue by following the documentation of VMware Cloud Foundation. " + Write-LogMessage -Type ERROR -Message "The vSAN cluster isn't in a healthy state. Check the messages above for a solution." Exit } if ( (Test-VsanObjectResync -cluster $cluster.name -server $vcServer.fqdn -user $vcUser -pass $vcPass) -eq 0) { - # Write-PowerManagementLogMessage -Type INFO -Message "vSAN object resynchronization is successful." + # Write-LogMessage -Type INFO -Message "vSAN object resynchronization is successful." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "There is an active vSAN object resynchronization operation. Check your environment and run the script again." + Write-LogMessage -Type ERROR -Message "There is an active vSAN object resynchronization operation. Check your environment and run the script again." Exit } } else { - Write-PowerManagementLogMessage -Type WARNING -Message "'$($vcServer.fqdn)' might already be shut down. Skipping the vSAN health check for cluster $($cluster.name)." + Write-LogMessage -Type WARNING -Message "'$($vcServer.fqdn)' might already be shut down. Skipping the vSAN health check for cluster $($cluster.name)." } # Verify that there are no running VMs on the ESXis and shutdown the vSAN cluster. @@ -649,15 +709,15 @@ Try { } } if ($runningVMs.count) { - Write-PowerManagementLogMessage -Type WARNING -Message "Some VMs are still in powered-on state." - Write-PowerManagementLogMessage -Type WARNING -Message "Cannot proceed until all VMs are shut down. Shut them down manually and run the script again." - Write-PowerManagementLogMessage -Type ERROR -Message "The environment has running VMs: $($runningVMs). Could not continue with vSAN shutdown while there are running VMs. Exiting! " + Write-LogMessage -Type WARNING -Message "Some VMs are still in powered-on state." + Write-LogMessage -Type WARNING -Message "Cannot proceed until all VMs are shut down. Shut them down manually and run the script again." + Write-LogMessage -Type ERROR -Message "The environment has running VMs: $($runningVMs). Could not continue with vSAN shutdown while there are running VMs. Exiting! " } else { if ([float]$vcfVersion -lt [float]4.5) { # Stop vSphere HA to avoid "orphaned" VMs during vSAN shutdown if (!$(Set-VsphereHA -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -disableHA)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Could not disable vSphere High Availability for cluster '$cluster'. Exiting!" + Write-LogMessage -Type ERROR -Message "Could not disable vSphere High Availability for cluster '$cluster'. Exiting!" } ## Actual vSAN and ESXi shutdown happens here - once we are sure that there are no VMs running on hosts @@ -667,7 +727,7 @@ Try { } # Run vSAN cluster preparation - should be done on one host per cluster # Sleeping 1 min before starting the preparation - Write-PowerManagementLogMessage -Type INFO -Message "Sleeping for one minute..." + Write-LogMessage -Type INFO -Message "Sleeping for one minute..." Start-Sleep -s 60 Invoke-EsxCommand -server $esxiDetails.fqdn[0] -user $esxiDetails.username[0] -pass $esxiDetails.password[0] -expected "Cluster preparation is done" -cmd "python /usr/lib/vmware/vsan/bin/reboot_helper.py prepare" # Putting hosts in maintenance mode @@ -682,7 +742,7 @@ Try { foreach ($esxiNode in $esxiDetails) { $hostConnectionState = Get-MaintenanceMode -server $esxiNode.fqdn -user $esxiNode.username -pass $esxiNode.password if ($hostConnectionState -eq "Maintenance") { - Write-PowerManagementLogMessage -Type ERROR -Message "$($esxiNode.fqdn) is in maintenance mode before cluster shutdown. Automation could not proceed. Check the vSphere Client for more details ." + Write-LogMessage -Type ERROR -Message "$($esxiNode.fqdn) is in maintenance mode before cluster shutdown. Automation could not proceed. Check the vSphere Client for more details ." Exit } } @@ -690,9 +750,9 @@ Try { # vSAN or VxRail Manager shutdown wizard automation. if ($vxRailDetails -ne "") { - Write-PowerManagementLogMessage -Type INFO -Message "Invoke VxRail cluster shutdown $($vxRailDetails.fqdn) $vcUser, and $vcPass" + Write-LogMessage -Type INFO -Message "Invoke VxRail cluster shutdown $($vxRailDetails.fqdn) $vcUser, and $vcPass" Invoke-VxrailClusterShutdown -server $vxRailDetails.fqdn -user $vcUser -pass $vcPass - Write-PowerManagementLogMessage -Type INFO -Message "Sleeping for 60 seconds before polling for ESXI hosts shutdown status check..." + Write-LogMessage -Type INFO -Message "Sleeping for 60 seconds before polling for ESXI hosts shutdown status check..." Start-Sleep -s 60 $counter = 0 @@ -703,14 +763,14 @@ Try { #Verify if all ESXi hosts are down in here to conclude End of Shutdown sequence foreach ($esxiNode in $esxiDetails) { if (Test-EndpointConnection -server $esxiNode.fqdn -port 443) { - Write-PowerManagementLogMessage -Type WARNING -Message "$($esxiNode.fqdn) is still up. Sleeping for $sleepTime seconds before next check..." + Write-LogMessage -Type WARNING -Message "$($esxiNode.fqdn) is still up. Sleeping for $sleepTime seconds before next check..." } else { $successCount++ } } if ($successCount -eq $esxiDetails.count) { - Write-PowerManagementLogMessage -Type INFO -Message "All Hosts have been shutdown successfully!" - Write-PowerManagementLogMessage -Type INFO -Message "End of the shutdown sequence!" + Write-LogMessage -Type INFO -Message "All Hosts have been shutdown successfully!" + Write-LogMessage -Type INFO -Message "End of the shutdown sequence!" Exit } else { Start-Sleep -s $sleepTime @@ -722,7 +782,7 @@ Try { Set-VsanClusterPowerStatus -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -PowerStatus clusterPoweredOff foreach ($esxiNode in $esxiDetails) { if (Test-EndpointConnection -server $esxiNode.fqdn -port 443) { - Write-PowerManagementLogMessage -Type ERROR -Message "$($esxiNode.fqdn) is still up. Check the FQDN or IP address, or the power state of the '$($esxiNode.fqdn)'." + Write-LogMessage -Type ERROR -Message "$($esxiNode.fqdn) is still up. Check the FQDN or IP address, or the power state of the '$($esxiNode.fqdn)'." Exit } } @@ -735,27 +795,27 @@ Try { # End of shutdown if ([float]$vcfVersion -lt [float]4.5) { - Write-PowerManagementLogMessage -Type INFO -Message "########################################################" - Write-PowerManagementLogMessage -Type INFO -Message "Note: ESXi hosts are still powered on. Please stop them manually." - Write-PowerManagementLogMessage -Type INFO -Message "End of the shutdown sequence for the specified cluster $($cluster.name)!" - Write-PowerManagementLogMessage -Type INFO -Message "########################################################" + Write-LogMessage -Type INFO -Message "########################################################" + Write-LogMessage -Type INFO -Message "Note: ESXi hosts are still powered on. Please stop them manually." + Write-LogMessage -Type INFO -Message "End of the shutdown sequence for the specified cluster $($cluster.name)!" + Write-LogMessage -Type INFO -Message "########################################################" } else { - Write-PowerManagementLogMessage -Type INFO -Message "########################################################" - Write-PowerManagementLogMessage -Type INFO -Message "End of the shutdown sequence for the specified cluster $($cluster.name)!" - Write-PowerManagementLogMessage -Type INFO -Message "########################################################" + Write-LogMessage -Type INFO -Message "########################################################" + Write-LogMessage -Type INFO -Message "End of the shutdown sequence for the specified cluster $($cluster.name)!" + Write-LogMessage -Type INFO -Message "########################################################" } } } $index += 1 } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } # Startup procedures Try { if ($WorkloadDomain.type -eq "MANAGEMENT") { - Write-PowerManagementLogMessage -Type ERROR -Message "The specified workload domain '$sddcDomain' is the management domain. This script handles only VI workload domains. Exiting! " + Write-LogMessage -Type ERROR -Message "The specified workload domain '$sddcDomain' is the management domain. This script handles only VI workload domains. Exiting! " Exit } @@ -773,12 +833,12 @@ Try { foreach ($esxiNode in $esxiDetails) { $status = Get-SSHEnabledStatus -server $esxiNode.fqdn -user $esxiNode.username -pass $esxiNode.password if (-Not $status) { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot open an SSH connection to host $($esxiNode.fqdn). If SSH is not enabled, follow the steps in the documentation to enable it." + Write-LogMessage -Type ERROR -Message "Cannot open an SSH connection to host $($esxiNode.fqdn). If SSH is not enabled, follow the steps in the documentation to enable it." Exit } } } Catch { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot open an SSH connection to host $($esxiNode.fqdn), If SSH is not enabled, follow the steps in the documentation to enable it." + Write-LogMessage -Type ERROR -Message "Cannot open an SSH connection to host $($esxiNode.fqdn), If SSH is not enabled, follow the steps in the documentation to enable it." } # Take hosts out of maintenance mode @@ -801,7 +861,7 @@ Try { } foreach ($cluster in $clusterDetails) { # Check ESXi status for each host - Write-PowerManagementLogMessage -Type INFO -Message "Checking the vSAN status of the ESXi hosts...." + Write-LogMessage -Type INFO -Message "Checking the vSAN status of the ESXi hosts...." $esxiDetails = $esxiWorkloadCluster[$cluster.name] foreach ($esxiNode in $esxiDetails) { Invoke-EsxCommand -server $esxiNode.fqdn -user $esxiNode.username -pass $esxiNode.password -expected "Local Node Health State: HEALTHY" -cmd "esxcli vsan cluster get" @@ -813,16 +873,16 @@ Try { # TODO - Do not run this for each cluster - we need to run it once per WLD. # We are starting all vCenter Servers, since we need to get NSX details. SDDC Manager needs VC connection to build this knowledge. # NSX Manager should be started after the VC, so if NSX manager is spanned across WLDs, we need to start all VCs. - Write-PowerManagementLogMessage -Type INFO -Message "Checking if all vCenter Servers in all workload domains are started." + Write-LogMessage -Type INFO -Message "Checking if all vCenter Servers in all workload domains are started." $serviceStatus = 0 foreach ($wldVC in $allWldVCs) { $vcStarted = (Get-VMsWithPowerStatus -server $mgmtVcServer.fqdn -user $mgmtVcUser -pass $mgmtVcPass -powerstate "poweredon" -pattern $wldVC.Split(".")[0] -silence).count if (-not $vcStarted) { # Startup the Virtual Infrastructure Workload Domain vCenter Server Start-CloudComponent -server $mgmtVcServer.fqdn -user $mgmtVcUser -pass $mgmtVcPass -nodes $wldVC.Split(".")[0] -timeout 600 - Write-PowerManagementLogMessage -Type INFO -Message "Waiting for the vCenter Server services to start on '$($wldVC.Split(".")[0])'. It will take some time." + Write-LogMessage -Type INFO -Message "Waiting for the vCenter Server services to start on '$($wldVC.Split(".")[0])'. It will take some time." } else { - Write-PowerManagementLogMessage -Type INFO -Message "vCenter Server '$($wldVC.Split(".")[0])' is already started" + Write-LogMessage -Type INFO -Message "vCenter Server '$($wldVC.Split(".")[0])' is already started" } $retries = 20 if ($DefaultVIServers) { @@ -838,7 +898,7 @@ Try { $serviceStatus += 1 break } else { - Write-PowerManagementLogMessage -Type INFO -Message "The services on vCenter Server $wldVC are still starting. Please wait." + Write-LogMessage -Type INFO -Message "The services on vCenter Server $wldVC are still starting. Please wait." Start-Sleep -s 60 } } @@ -846,7 +906,7 @@ Try { # Workaround for ESXis that do not communicate their Maintenance status to vCenter Server foreach ($esxiNode in $esxiDetails) { if ((Get-VMHost -Name $esxiNode.fqdn).ConnectionState -eq "Maintenance") { - Write-PowerManagementLogMessage -Type INFO -Message "Performing exit maintenance mode on '$($esxiNode.fqdn)' from vCenter Server." + Write-LogMessage -Type INFO -Message "Performing exit maintenance mode on '$($esxiNode.fqdn)' from vCenter Server." (Get-VMHost -Name $esxiNode.fqdn | Get-View).ExitMaintenanceMode_Task(0) | Out-Null } } @@ -856,12 +916,12 @@ Try { } Start-Sleep -s 60 $retries -= 1 - Write-PowerManagementLogMessage -Type INFO -Message "vCenter Server is still starting. Please wait." + Write-LogMessage -Type INFO -Message "vCenter Server is still starting. Please wait." } } if ($serviceStatus -eq $allWldVCs.count) { - Write-PowerManagementLogMessage -Type INFO -Message "vCenter Server has been started successfully." + Write-LogMessage -Type INFO -Message "vCenter Server has been started successfully." if ([float]$vcfVersion -gt [float]4.4) { #Start ESXi hosts here # TODO - Check if this workaround is needed for VCF 5.1 and newer. @@ -881,16 +941,16 @@ Try { } $proceed = Read-Host $warningString if (-Not $proceed) { - Write-PowerManagementLogMessage -Type WARNING -Message "None of the options is selected. Default is 'No', hence stopping script execution." + Write-LogMessage -Type WARNING -Message "None of the options is selected. Default is 'No', hence stopping script execution." Exit } else { if (($proceed -match "no") -or ($proceed -match "yes")) { if ($proceed -match "no") { - Write-PowerManagementLogMessage -Type WARNING -Message "Stopping script execution because the input is 'No'." + Write-LogMessage -Type WARNING -Message "Stopping script execution because the input is 'No'." Exit } } else { - Write-PowerManagementLogMessage -Type WARNING -Message "Pass the right string - either 'Yes' or 'No'." + Write-LogMessage -Type WARNING -Message "Pass the right string - either 'Yes' or 'No'." Exit } } @@ -898,7 +958,7 @@ Try { $esxiDetails = $esxiWorkloadCluster[$cluster.name] foreach ($esxiNode in $esxiDetails) { if (!(Test-EndpointConnection -server $esxiNode.fqdn -port 443)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot communicate with the host $($esxiNode.fqdn). Check the FQDN or IP address, or the power state of '$($esxiNode.fqdn)'." + Write-LogMessage -Type ERROR -Message "Cannot communicate with the host $($esxiNode.fqdn). Check the FQDN or IP address, or the power state of '$($esxiNode.fqdn)'." Exit } } @@ -913,33 +973,33 @@ Try { foreach ($esxiNode in $esxiDetails) { $hostConnectionState = Get-MaintenanceMode -server $esxiNode.fqdn -user $esxiNode.username -pass $esxiNode.password if ($hostConnectionState -eq "Maintenance") { - Write-PowerManagementLogMessage -Type ERROR -Message "$($esxiNode.fqdn) is still in maintenance mode even after cluster restart. Check the vSphere Client and take the necessary actions." + Write-LogMessage -Type ERROR -Message "$($esxiNode.fqdn) is still in maintenance mode even after cluster restart. Check the vSphere Client and take the necessary actions." Exit } } } if ((Test-VsanHealth -cluster $cluster.name -server $vcServer.fqdn -user $vcUser -pass $vcPass) -eq 0) { - Write-PowerManagementLogMessage -Type INFO -Message "Cluster health is good." + Write-LogMessage -Type INFO -Message "Cluster health is good." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "The cluster isn't in a healthy state. Check your environment and run the script again." + Write-LogMessage -Type ERROR -Message "The cluster isn't in a healthy state. Check your environment and run the script again." Exit } # Check the health and sync status of the vSAN cluster if ((Test-VsanObjectResync -cluster $cluster.name -server $vcServer.fqdn -user $vcUser -pass $vcPass) -eq 0) { - # Write-PowerManagementLogMessage -Type INFO -Message "vSAN object resynchronization is successful." + # Write-LogMessage -Type INFO -Message "vSAN object resynchronization is successful." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "vSAN object resynchronization has failed. Check your environment and run the script again." + Write-LogMessage -Type ERROR -Message "vSAN object resynchronization has failed. Check your environment and run the script again." Exit } if ([float]$vcfVersion -lt [float]4.5) { # Start vSphere HA to avoid triggering a "Cannot find vSphere HA master agent" error. if (!$(Set-VsphereHA -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -enableHA)) { - Write-PowerManagementLogMessage -Type ERROR -Message "Could not enable vSphere High Availability for cluster '$cluster'. Exiting!" + Write-LogMessage -Type ERROR -Message "Could not enable vSphere High Availability for cluster '$cluster'. Exiting!" } } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Some of the vCenter Server instances are not started. Check the vSphere Client for more details and run the script again after all vCenter Server instances are up and running." + Write-LogMessage -Type ERROR -Message "Some of the vCenter Server instances are not started. Check the vSphere Client for more details and run the script again after all vCenter Server instances are up and running." Exit } } @@ -948,7 +1008,7 @@ Try { foreach ($cluster in $clusterDetails) { # Startup vSphere Cluster Services Virtual Machines in Virtual Infrastructure Workload Domain Set-RetreatMode -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -mode disable - Write-PowerManagementLogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS startup will take some time. Please wait! " + Write-LogMessage -Type INFO -Message "vCLS retreat mode has been set. vCLS startup will take some time. Please wait! " } $index = 1 @@ -960,7 +1020,7 @@ Try { while ($counter -ne $retries) { $powerOnVMcount = (Get-VMToClusterMapping -server $vcServer.fqdn -user $vcUser -pass $vcPass -powerstate "poweredon" -cluster $cluster.name -folder "vcls" -silence).count if ( $powerOnVMcount -lt 3 ) { - Write-PowerManagementLogMessage -Type INFO -Message "There are $powerOnVMcount vCLS virtual machines running. Sleeping for $sleepTime seconds until the next check..." + Write-LogMessage -Type INFO -Message "There are $powerOnVMcount vCLS virtual machines running. Sleeping for $sleepTime seconds until the next check..." Start-Sleep -s $sleepTime $counter += 1 } else { @@ -968,27 +1028,27 @@ Try { } } if ($counter -eq $retries) { - Write-PowerManagementLogMessage -Type ERROR -Message "The vCLS VMs were not started within the expected time. Stopping script execution!" + Write-LogMessage -Type ERROR -Message "The vCLS VMs were not started within the expected time. Stopping script execution!" Exit } [Array]$clusterVclsVMs = @() [Array]$clusterVcfVMs = @() - Write-PowerManagementLogMessage -Type INFO -Message "Trying to fetch virtual machines for the specified vSphere cluster $($cluster.name)..." + Write-LogMessage -Type INFO -Message "Trying to fetch virtual machines for the specified vSphere cluster $($cluster.name)..." [Array]$clusterAllVMs = Get-VMToClusterMapping -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -folder "VM" - Write-PowerManagementLogMessage -Type INFO -Message "Trying to fetch information about the vCLS virtual machines for the specified vSphere cluster $($cluster.name)..." + Write-LogMessage -Type INFO -Message "Trying to fetch information about the vCLS virtual machines for the specified vSphere cluster $($cluster.name)..." [Array]$clusterVclsVMs = Get-VMToClusterMapping -server $vcServer.fqdn -user $vcUser -pass $vcPass -cluster $cluster.name -folder "vcls" foreach ($vm in $clusterVclsVMs) { [Array]$clusterVcfVMs += $vm } $vcfVMs += $vcServer.fqdn.Split(".")[0] $clusterVcfVMs += $vcServer.fqdn.Split(".")[0] - Write-PowerManagementLogMessage -Type INFO -Message "Trying to fetch information about customer virtual machines for the specified vSphere cluster $($cluster.name)..." + Write-LogMessage -Type INFO -Message "Trying to fetch information about customer virtual machines for the specified vSphere cluster $($cluster.name)..." $clusterCustomerVMs = $clusterAllVMs | Where-Object { $vcfVMs -NotContains $_ } if ($index -eq 1) { # Get fresh token from SDDC manager $statusMsg = Request-VCFToken -fqdn $server -username $user -password $pass -WarningAction SilentlyContinue -ErrorAction SilentlyContinue -WarningVariable WarnMsg -ErrorVariable ErrorMsg - if ($statusMsg) { Write-PowerManagementLogMessage -Type INFO -Message $statusMsg } if ($warnMsg) { Write-PowerManagementLogMessage -Type WARNING -Message $warnMsg } if ($ErrorMsg) { Write-PowerManagementLogMessage -Type ERROR -Message $ErrorMsg } + if ($statusMsg) { Write-LogMessage -Type INFO -Message $statusMsg } if ($warnMsg) { Write-LogMessage -Type WARNING -Message $warnMsg } if ($ErrorMsg) { Write-LogMessage -Type ERROR -Message $ErrorMsg } # Get NSX-T Details once VC is started ## Gather NSX Manager Cluster Details @@ -999,20 +1059,20 @@ Try { Try { $nsxtCluster = Get-VCFNsxtCluster -id $workloadDomain.nsxtCluster.id -ErrorAction SilentlyContinue -InformationAction Ignore } Catch { - Write-PowerManagementLogMessage -Type INFO -Message "SDDC Manager is still retrieving NSX-T Data Center information. Sleeping for $sleepTime seconds until the next check..." + Write-LogMessage -Type INFO -Message "SDDC Manager is still retrieving NSX-T Data Center information. Sleeping for $sleepTime seconds until the next check..." Start-Sleep -s $sleepTime $counter += 1 } # Stop loop if we have FQDN for NSX-T VIP if ( $($nsxtCluster.vipFqdn) ) { Break } else { - Write-PowerManagementLogMessage -Type INFO -Message "SDDC Manager is still retrieving NSX-T Data Center information. Sleeping for $sleepTime seconds until the next check..." + Write-LogMessage -Type INFO -Message "SDDC Manager is still retrieving NSX-T Data Center information. Sleeping for $sleepTime seconds until the next check..." Start-Sleep -s $sleepTime $counter += 1 } } if ($counter -eq $retries) { - Write-PowerManagementLogMessage -Type ERROR -Message "SDDC Manager did not manage to retrieve NSX-T Data Center information. Please check the LCM log file for errors. Stopping the script execution!" + Write-LogMessage -Type ERROR -Message "SDDC Manager did not manage to retrieve NSX-T Data Center information. Please check the LCM log file for errors. Stopping the script execution!" Exit } $nsxtManagerFQDN = $nsxtCluster.vipFqdn @@ -1030,18 +1090,18 @@ Try { $nsxtStarted = 0 foreach ($node in $nsxtNodes) { - Write-PowerManagementLogMessage -Type INFO -Message "Checking if $node is already started." + Write-LogMessage -Type INFO -Message "Checking if $node is already started." $nsxtStarted += (Get-VMsWithPowerStatus -server $mgmtVcServer.fqdn -user $mgmtVcUser -pass $mgmtVcPass -powerstate "poweredon" -pattern $node -silence).count } if (-not ($nsxtStarted -eq $nsxtNodes.count)) { # Startup the NSX Manager Nodes for Virtual Infrastructure Workload Domain Start-CloudComponent -server $mgmtVcServer.fqdn -user $mgmtVcUser -pass $mgmtVcPass -nodes $nsxtNodes -timeout 600 if (!(Wait-ForStableNsxtClusterStatus -server $nsxtManagerFQDN -user $nsxtManagerVIP.adminUser -pass $nsxtManagerVIP.adminPassword)) { - Write-PowerManagementLogMessage -Type ERROR -Message "The NSX Manager cluster is not in 'STABLE' state. Exiting!" + Write-LogMessage -Type ERROR -Message "The NSX Manager cluster is not in 'STABLE' state. Exiting!" Exit } } else { - Write-PowerManagementLogMessage -Type INFO -Message "NSX Manager is already started." + Write-LogMessage -Type INFO -Message "NSX Manager is already started." } } @@ -1060,38 +1120,38 @@ Try { [Array]$vcfVMs += $node } } Catch { - Write-PowerManagementLogMessage -Type WARNING -Message "Cannot fetch information about NSX Edge nodes." + Write-LogMessage -Type WARNING -Message "Cannot fetch information about NSX Edge nodes." } if ($nsxtClusterEdgeNodes.count -ne 0) { Start-CloudComponent -server $vcServer.fqdn -user $vcUser -pass $vcPass -nodes $nsxtClusterEdgeNodes -timeout 600 } else { - Write-PowerManagementLogMessage -Type WARNING -Message "No NSX Edge nodes found. Skipping edge nodes startup for vSAN cluster '$($cluster.name)'!" + Write-LogMessage -Type WARNING -Message "No NSX Edge nodes found. Skipping edge nodes startup for vSAN cluster '$($cluster.name)'!" } # End of startup $vcfVMs_string = "" $vcfVMs_string = ($clusterVcfVMs | Select-Object -Unique) -join "; " - Write-PowerManagementLogMessage -Type INFO -Message "##################################################################################" - Write-PowerManagementLogMessage -Type INFO -Message "The following components have been started: $vcfVMs_string ." + Write-LogMessage -Type INFO -Message "##################################################################################" + Write-LogMessage -Type INFO -Message "The following components have been started: $vcfVMs_string ." if ([float]$vcfVersion -lt [float]4.5) { - Write-PowerManagementLogMessage -Type INFO -Message "vSphere High Availability has been enabled by the script. Disable it per your environment's design." + Write-LogMessage -Type INFO -Message "vSphere High Availability has been enabled by the script. Disable it per your environment's design." } - Write-PowerManagementLogMessage -Type INFO -Message "Check the list above and start any additional VMs, that are required, before you proceed with workload startup!" - Write-PowerManagementLogMessage -Type INFO -Message "Use the following command to automatically start VMs" - Write-PowerManagementLogMessage -Type INFO -Message "Start-CloudComponent -server $($vcServer.fqdn) -user $vcUser -pass $vcPass -nodes -timeout 600" + Write-LogMessage -Type INFO -Message "Check the list above and start any additional VMs, that are required, before you proceed with workload startup!" + Write-LogMessage -Type INFO -Message "Use the following command to automatically start VMs" + Write-LogMessage -Type INFO -Message "Start-CloudComponent -server $($vcServer.fqdn) -user $vcUser -pass $vcPass -nodes -timeout 600" if ([float]$vcfVersion -lt [float]4.5) { - Write-PowerManagementLogMessage -Type WARNING -Message "If you have enabled SSH for the ESXi hosts through SDDC manager, disable it at this point." + Write-LogMessage -Type WARNING -Message "If you have enabled SSH for the ESXi hosts through SDDC manager, disable it at this point." } if ([float]$vcfVersion -gt [float]4.4) { - Write-PowerManagementLogMessage -Type WARNING -Message "If you have disabled lockdown mode for the ESXi hosts in workload cluster, you can enable it at this point." + Write-LogMessage -Type WARNING -Message "If you have disabled lockdown mode for the ESXi hosts in workload cluster, you can enable it at this point." } - Write-PowerManagementLogMessage -Type INFO -Message "##################################################################################" - Write-PowerManagementLogMessage -Type INFO -Message "End of startup sequence for the cluster '$($cluster.name)'!" - Write-PowerManagementLogMessage -Type INFO -Message "##################################################################################" + Write-LogMessage -Type INFO -Message "##################################################################################" + Write-LogMessage -Type INFO -Message "End of startup sequence for the cluster '$($cluster.name)'!" + Write-LogMessage -Type INFO -Message "##################################################################################" $index += 1 } } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } diff --git a/VMware.CloudFoundation.PowerManagement.psm1 b/VMware.CloudFoundation.PowerManagement.psm1 index 88b110f..268c835 100644 --- a/VMware.CloudFoundation.PowerManagement.psm1 +++ b/VMware.CloudFoundation.PowerManagement.psm1 @@ -109,10 +109,10 @@ Function Stop-CloudComponent { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Stop-CloudComponent cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Stop-CloudComponent cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } @@ -120,22 +120,22 @@ Function Stop-CloudComponent { if ($DefaultVIServer.Name -EQ $server) { if ($PSCmdlet.ParameterSetName -EQ "Node") { $nodes_string = $nodes -join "; " - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server' and attempting to shut down nodes '$nodes_string'..." + Write-LogMessage -Type INFO -Message "Connected to server '$server' and attempting to shut down nodes '$nodes_string'..." if ($nodes.Count -ne 0) { foreach ($node in $nodes) { $count = 0 if (Get-VM | Where-Object { $_.Name -EQ $node }) { $vmObject = Get-VMGuest -Server $server -VM $node -ErrorAction SilentlyContinue if ($vmObject.State -EQ 'NotRunning') { - Write-PowerManagementLogMessage -Type INFO -Message "Node '$node' is already powered off." + Write-LogMessage -Type INFO -Message "Node '$node' is already powered off." Continue } - Write-PowerManagementLogMessage -Type INFO -Message "Attempting to shut down node '$node'..." + Write-LogMessage -Type INFO -Message "Attempting to shut down node '$node'..." if ($PsBoundParameters.ContainsKey("noWait")) { Stop-VM -Server $server -VM $node -Confirm:$false -ErrorAction SilentlyContinue | Out-Null } else { Stop-VMGuest -Server $server -VM $node -Confirm:$false -ErrorAction SilentlyContinue | Out-Null - Write-PowerManagementLogMessage -Type INFO -Message "Waiting for node '$node' to shut down..." + Write-LogMessage -Type INFO -Message "Waiting for node '$node' to shut down..." $sleepTime = 5 While (($vmObject.State -ne 'NotRunning') -and ($count -le $timeout)) { Start-Sleep -s $sleepTime @@ -143,20 +143,20 @@ Function Stop-CloudComponent { $vmObject = Get-VMGuest -Server $server -VM $node -ErrorAction SilentlyContinue } if ($count -gt $timeout) { - Write-PowerManagementLogMessage -Type ERROR -Message "Node '$node' did not shut down within the expected timeout $timeout value." + Write-LogMessage -Type ERROR -Message "Node '$node' did not shut down within the expected timeout $timeout value." } else { - Write-PowerManagementLogMessage -Type INFO -Message "Node '$node' has shut down successfully." + Write-LogMessage -Type INFO -Message "Node '$node' has shut down successfully." } } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Unable to find node '$node' in the inventory of server '$server'." + Write-LogMessage -Type ERROR -Message "Unable to find node '$node' in the inventory of server '$server'." } } } } if ($PSCmdlet.ParameterSetName -EQ "Pattern") { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server' and attempting to shut down nodes with pattern '$pattern'..." + Write-LogMessage -Type INFO -Message "Connected to server '$server' and attempting to shut down nodes with pattern '$pattern'..." if ($pattern) { $patternNodes = Get-VM -Server $server | Where-Object Name -Match $pattern | Select-Object Name, PowerState, VMHost | Where-Object VMHost -Match $server } else { @@ -167,10 +167,10 @@ Function Stop-CloudComponent { $count = 0 $vmObject = Get-VMGuest -Server $server -VM $node.Name | Where-Object VmUid -Match $server if ($vmObject.State -EQ 'NotRunning') { - Write-PowerManagementLogMessage -Type INFO -Message "Node '$($node.name)' is already powered off." + Write-LogMessage -Type INFO -Message "Node '$($node.name)' is already powered off." Continue } - Write-PowerManagementLogMessage -Type INFO -Message "Attempting to shut down node '$($node.name)'..." + Write-LogMessage -Type INFO -Message "Attempting to shut down node '$($node.name)'..." if ($PsBoundParameters.ContainsKey("noWait")) { Stop-VM -Server $server -VM $node.Name -Confirm:$false | Out-Null } else { @@ -183,27 +183,27 @@ Function Stop-CloudComponent { $vmObject = Get-VMGuest -VM $node.Name | Where-Object VmUid -Match $server } if ($count -gt $timeout) { - Write-PowerManagementLogMessage -Type ERROR -Message "Node '$($node.name)' did not shut down within the expected timeout $timeout value." + Write-LogMessage -Type ERROR -Message "Node '$($node.name)' did not shut down within the expected timeout $timeout value." } else { - Write-PowerManagementLogMessage -Type INFO -Message "Node '$($node.name)' has shut down successfully." + Write-LogMessage -Type INFO -Message "Node '$($node.name)' has shut down successfully." } } } } elseif ($pattern) { - Write-PowerManagementLogMessage -Type WARNING -Message "No nodes match pattern '$pattern' on host '$server'." + Write-LogMessage -Type WARNING -Message "No nodes match pattern '$pattern' on host '$server'." } } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Stop-CloudComponent cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Stop-CloudComponent cmdlet." } } Export-ModuleMember -Function Stop-CloudComponent @@ -255,10 +255,10 @@ Function Start-CloudComponent { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Start-CloudComponent cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Start-CloudComponent cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } @@ -266,41 +266,41 @@ Function Start-CloudComponent { if ($DefaultVIServer.Name -EQ $server) { if ($PSCmdlet.ParameterSetName -EQ "Node") { $nodes_string = $nodes -join "; " - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server' and attempting to start nodes '$nodes_string'." + Write-LogMessage -Type INFO -Message "Connected to server '$server' and attempting to start nodes '$nodes_string'." if ($nodes.Count -ne 0) { foreach ($node in $nodes) { $count = 0 if (Get-VM | Where-Object { $_.Name -EQ $node }) { $vmObject = Get-VMGuest -Server $server -VM $node -ErrorAction SilentlyContinue if ($vmObject.State -EQ 'Running') { - Write-PowerManagementLogMessage -Type INFO -Message "Node '$node' is already in powered on." + Write-LogMessage -Type INFO -Message "Node '$node' is already in powered on." Continue } - Write-PowerManagementLogMessage -Type INFO -Message "Attempting to start up node '$node'..." + Write-LogMessage -Type INFO -Message "Attempting to start up node '$node'..." Start-VM -VM $node -Confirm:$false -ErrorAction SilentlyContinue | Out-Null Start-Sleep -s 5 $sleepTime = 10 - Write-PowerManagementLogMessage -Type INFO -Message "Waiting for node '$node' to start up..." + Write-LogMessage -Type INFO -Message "Waiting for node '$node' to start up..." While (($vmObject.State -ne 'Running') -and ($count -le $timeout)) { Start-Sleep -s $sleepTime $count = $count + $sleepTime $vmObject = Get-VMGuest -Server $server -VM $node -ErrorAction SilentlyContinue } if ($count -gt $timeout) { - Write-PowerManagementLogMessage -Type ERROR -Message "Node '$node' did not start up within the expected timeout $timeout value." + Write-LogMessage -Type ERROR -Message "Node '$node' did not start up within the expected timeout $timeout value." Break } else { - Write-PowerManagementLogMessage -Type INFO -Message "Node '$node' has started successfully." + Write-LogMessage -Type INFO -Message "Node '$node' has started successfully." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot find '$node' in the inventory of host '$server'." + Write-LogMessage -Type ERROR -Message "Cannot find '$node' in the inventory of host '$server'." } } } } if ($PSCmdlet.ParameterSetName -EQ "Pattern") { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to host '$server' and attempting to start up nodes with pattern '$pattern'..." + Write-LogMessage -Type INFO -Message "Connected to host '$server' and attempting to start up nodes with pattern '$pattern'..." if ($pattern) { $patternNodes = Get-VM -Server $server | Where-Object Name -Match $pattern | Select-Object Name, PowerState, VMHost | Where-Object VMHost -Match $server } else { @@ -311,40 +311,40 @@ Function Start-CloudComponent { $count = 0 $vmObject = Get-VMGuest -server $server -VM $node.Name | Where-Object VmUid -Match $server if ($vmObject.State -EQ 'Running') { - Write-PowerManagementLogMessage -Type INFO -Message "Node '$($node.name)' is already powered on." + Write-LogMessage -Type INFO -Message "Node '$($node.name)' is already powered on." Continue } Start-VM -VM $node.Name | Out-Null $sleepTime = 1 $vmObject = Get-VMGuest -Server $server -VM $node.Name | Where-Object VmUid -Match $server - Write-PowerManagementLogMessage -Type INFO -Message "Attempting to start up node '$($node.name)'..." + Write-LogMessage -Type INFO -Message "Attempting to start up node '$($node.name)'..." While (($vmObject.State -ne 'Running') -AND ($count -le $timeout)) { Start-Sleep -s $sleepTime $count = $count + $sleepTime $vmObject = Get-VMGuest -Server $server -VM $node.Name | Where-Object VmUid -Match $server } if ($count -gt $timeout) { - Write-PowerManagementLogMessage -Type ERROR -Message "Node '$($node.name)' did not start up within the expected timeout $timeout value." + Write-LogMessage -Type ERROR -Message "Node '$($node.name)' did not start up within the expected timeout $timeout value." } else { - Write-PowerManagementLogMessage -Type INFO -Message "Node '$($node.name)' has started successfully." + Write-LogMessage -Type INFO -Message "Node '$($node.name)' has started successfully." } } } elseif ($pattern) { - Write-PowerManagementLogMessage -Type WARNING -Message "No nodes match pattern '$pattern' on host '$server'." + Write-LogMessage -Type WARNING -Message "No nodes match pattern '$pattern' on host '$server'." } } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to host '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to host '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Start-CloudComponent cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Start-CloudComponent cmdlet." } } Export-ModuleMember -Function Start-CloudComponent @@ -388,62 +388,62 @@ Function Set-MaintenanceMode { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Set-MaintenanceMode cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Set-MaintenanceMode cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null if ($DefaultVIServer.Name -EQ $server) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server' and attempting to $state maintenance mode..." + Write-LogMessage -Type INFO -Message "Connected to server '$server' and attempting to $state maintenance mode..." $hostStatus = (Get-VMHost -Server $server) if ($state -EQ "ENABLE") { if ($hostStatus.ConnectionState -EQ "Connected") { - Write-PowerManagementLogMessage -Type INFO -Message "Attempting to enter maintenance mode for '$server'..." + Write-LogMessage -Type INFO -Message "Attempting to enter maintenance mode for '$server'..." Get-View -Server $server -ViewType HostSystem -Filter @{"Name" = $server } | Where-Object { !$_.Runtime.InMaintenanceMode } | ForEach-Object { $_.EnterMaintenanceMode(0, $false, (New-Object VMware.Vim.HostMaintenanceSpec -Property @{vsanMode = (New-Object VMware.Vim.VsanHostDecommissionMode -Property @{objectAction = [VMware.Vim.VsanHostDecommissionModeObjectAction]::NoAction }) })) } | Out-Null $hostStatus = (Get-VMHost -Server $server) if ($hostStatus.ConnectionState -EQ "Maintenance") { - Write-PowerManagementLogMessage -Type INFO -Message "Host '$server' has entered maintenance mode successfully." + Write-LogMessage -Type INFO -Message "Host '$server' has entered maintenance mode successfully." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Host '$server' did not enter maintenance mode. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Host '$server' did not enter maintenance mode. Check your environment and try again." } } elseif ($hostStatus.ConnectionState -EQ "Maintenance") { - Write-PowerManagementLogMessage -Type INFO -Message "Host '$server' has already entered maintenance mode." + Write-LogMessage -Type INFO -Message "Host '$server' has already entered maintenance mode." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Host '$server' is not currently connected." + Write-LogMessage -Type ERROR -Message "Host '$server' is not currently connected." } } elseif ($state -EQ "DISABLE") { if ($hostStatus.ConnectionState -EQ "Maintenance") { - Write-PowerManagementLogMessage -Type INFO -Message "Attempting to exit maintenance mode for '$server'..." + Write-LogMessage -Type INFO -Message "Attempting to exit maintenance mode for '$server'..." $task = Set-VMHost -VMHost $server -State "Connected" -RunAsync -WarningAction SilentlyContinue -ErrorAction SilentlyContinue Wait-Task $task | Out-Null $hostStatus = (Get-VMHost -Server $server) if ($hostStatus.ConnectionState -EQ "Connected") { - Write-PowerManagementLogMessage -Type INFO -Message "Host '$server' has exited maintenance mode successfully." + Write-LogMessage -Type INFO -Message "Host '$server' has exited maintenance mode successfully." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "The host '$server' did not exit maintenance mode. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "The host '$server' did not exit maintenance mode. Check your environment and try again." } } elseif ($hostStatus.ConnectionState -EQ "Connected") { - Write-PowerManagementLogMessage -Type INFO -Message "Host '$server' has already exited maintenance mode" + Write-LogMessage -Type INFO -Message "Host '$server' has already exited maintenance mode" } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Host '$server' is not currently connected." + Write-LogMessage -Type ERROR -Message "Host '$server' is not currently connected." } } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Set-MaintenanceMode cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Set-MaintenanceMode cmdlet." } } Export-ModuleMember -Function Set-MaintenanceMode @@ -479,29 +479,29 @@ Function Get-MaintenanceMode { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-MaintenanceMode cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Get-MaintenanceMode cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null if ($DefaultVIServer.Name -EQ $server) { $hostStatus = (Get-VMHost -Server $server) - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server'. The connection status is '$($hostStatus.ConnectionState)'." + Write-LogMessage -Type INFO -Message "Connected to server '$server'. The connection status is '$($hostStatus.ConnectionState)'." Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null return $hostStatus.ConnectionState } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again." } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-MaintenanceMode cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Get-MaintenanceMode cmdlet." } } Export-ModuleMember -Function Get-MaintenanceMode @@ -545,11 +545,11 @@ Function Set-DrsAutomationLevel { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Set-DrsAutomationLevel cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Set-DrsAutomationLevel cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } @@ -558,29 +558,29 @@ Function Set-DrsAutomationLevel { $drsStatus = Get-Cluster -Name $cluster -ErrorAction SilentlyContinue if ($drsStatus) { if ($drsStatus.DrsAutomationLevel -EQ $level) { - Write-PowerManagementLogMessage -Type INFO -Message "The vSphere DRS automation level for cluster '$cluster' is already '$level'." + Write-LogMessage -Type INFO -Message "The vSphere DRS automation level for cluster '$cluster' is already '$level'." } else { $drsStatus = Set-Cluster -Cluster $cluster -DrsAutomationLevel $level -Confirm:$false if ($drsStatus.DrsAutomationLevel -EQ $level) { - Write-PowerManagementLogMessage -Type INFO -Message "The vSphere DRS automation level for cluster '$cluster' has been set to '$level' successfully." + Write-LogMessage -Type INFO -Message "The vSphere DRS automation level for cluster '$cluster' has been set to '$level' successfully." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Failed to set the vSphere DRS automation level for cluster '$cluster' to '$level'." + Write-LogMessage -Type ERROR -Message "Failed to set the vSphere DRS automation level for cluster '$cluster' to '$level'." } } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cluster '$cluster' not found on host '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cluster '$cluster' not found on host '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Set-DrsAutomationLevel cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Set-DrsAutomationLevel cmdlet." } } Export-ModuleMember -Function Set-DrsAutomationLevel @@ -631,11 +631,11 @@ Function Set-VsanClusterPowerStatus { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Set-VsanClusterPowerStatus cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Set-VsanClusterPowerStatus cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } @@ -663,7 +663,7 @@ Function Set-VsanClusterPowerStatus { do { $task = Get-Task -Id $powerActionTask if (-Not ($task.State -EQ "Error")) { - Write-PowerManagementLogMessage -Type INFO -Message "$PowerStatus task is $($task.PercentComplete)% completed." + Write-LogMessage -Type INFO -Message "$PowerStatus task is $($task.PercentComplete)% completed." } Start-Sleep -s $sleepTime $counter += $sleepTime @@ -671,31 +671,31 @@ Function Set-VsanClusterPowerStatus { if ($task.State -EQ "Error") { if ($task.ExtensionData.Info.Error.Fault.FaultMessage -like "VMware.Vim.LocalizableMessage") { - Write-PowerManagementLogMessage -Type ERROR -Message "'$($PowerStatus)' task exited with a localized error message. Go to the vSphere Client for details and to take the necessary actions." + Write-LogMessage -Type ERROR -Message "'$($PowerStatus)' task exited with a localized error message. Go to the vSphere Client for details and to take the necessary actions." } else { - Write-PowerManagementLogMessage -Type WARN -Message "'$($PowerStatus)' task exited with the Message:$($task.ExtensionData.Info.Error.Fault.FaultMessage) and Error: $($task.ExtensionData.Info.Error)." - Write-PowerManagementLogMessage -Type ERROR -Message "Go to the vSphere Client for details and to take the necessary actions." + Write-LogMessage -Type WARN -Message "'$($PowerStatus)' task exited with the Message:$($task.ExtensionData.Info.Error.Fault.FaultMessage) and Error: $($task.ExtensionData.Info.Error)." + Write-LogMessage -Type ERROR -Message "Go to the vSphere Client for details and to take the necessary actions." } } if ($task.State -EQ "Success") { - Write-PowerManagementLogMessage -Type INFO -Message "$PowerStatus task is completed successfully." + Write-LogMessage -Type INFO -Message "$PowerStatus task is completed successfully." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "$PowerStatus task is blocked in $($task.State) state." + Write-LogMessage -Type ERROR -Message "$PowerStatus task is blocked in $($task.State) state." } } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Set-VsanClusterPowerStatus cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Set-VsanClusterPowerStatus cmdlet." } } Export-ModuleMember -Function Set-VsanClusterPowerStatus @@ -721,11 +721,11 @@ Function Invoke-VxrailClusterShutdown { ) Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Invoke-VxrailClusterShutdown cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Invoke-VxrailClusterShutdown cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } @@ -738,11 +738,11 @@ Function Invoke-VxrailClusterShutdown { $headers.Add("Authorization", "Basic $base64AuthInfo") $uri = "https://$server/rest/vxm/v1/cluster/shutdown" - Write-PowerManagementLogMessage -Type INFO -Message "Starting VxRail cluster shutdown dry run." + Write-LogMessage -Type INFO -Message "Starting VxRail cluster shutdown dry run." $respond = Invoke-WebRequest -Method POST -Uri $uri -Headers $headers -Body $payloadTest -UseBasicParsing -SkipCertificateCheck if ($respond.StatusCode -EQ "202" -or $respond.StatusCode -EQ "200") { $requestID = $respond.content | ConvertFrom-Json - Write-PowerManagementLogMessage -Type INFO -Message "VxRail cluster shutdown request accepted(ID:$($requestID.request_id))" + Write-LogMessage -Type INFO -Message "VxRail cluster shutdown request accepted(ID:$($requestID.request_id))" $uri2 = "https://$server/rest/vxm/v1/requests/$($requestID.request_id)" $loopCounter = 0 $loopCounterLimit = 13 @@ -759,14 +759,14 @@ Function Invoke-VxrailClusterShutdown { } if ($checkProgress.extension.passed -match "true") { - Write-PowerManagementLogMessage -Type INFO -Message "VxRail cluster shutdown dry run: SUCCEEDED." - Write-PowerManagementLogMessage -Type INFO -Message "Starting VxRail cluster shutdown." + Write-LogMessage -Type INFO -Message "VxRail cluster shutdown dry run: SUCCEEDED." + Write-LogMessage -Type INFO -Message "Starting VxRail cluster shutdown." $respond = Invoke-WebRequest -Method POST -Uri $uri -Headers $headers -Body $payloadRun -UseBasicParsing -SkipCertificateCheck if ($respond.StatusCode -EQ "202" -or $respond.StatusCode -EQ "200") { return $true } else { - Write-PowerManagementLogMessage -Type ERROR -Message "VxRail cluster shutdown: FAILED" + Write-LogMessage -Type ERROR -Message "VxRail cluster shutdown: FAILED" } } else { $errorMsg = "" @@ -777,18 +777,18 @@ Function Invoke-VxrailClusterShutdown { $errorMsg = $errorMsg + "Label: $($errorElement.label),($($errorElement.checkResult)) `nMessage: $($errorElement.message)`n" } } - Write-PowerManagementLogMessage -Type ERROR -Message "VxRail cluster shutdown dry run: FAILED `n $errorMsg" + Write-LogMessage -Type ERROR -Message "VxRail cluster shutdown dry run: FAILED `n $errorMsg" } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "VxRail cluster shutdown: FAILED" + Write-LogMessage -Type ERROR -Message "VxRail cluster shutdown: FAILED" } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Invoke-VxrailClusterShutdown cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Invoke-VxrailClusterShutdown cmdlet." } } Export-ModuleMember -Function Invoke-VxrailClusterShutdown @@ -828,11 +828,11 @@ Function Get-poweronVMsOnRemoteDS { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-poweronVMsOnRemoteDS cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Get-poweronVMsOnRemoteDS cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } @@ -853,7 +853,7 @@ Function Get-poweronVMsOnRemoteDS { $datastoreID = Get-Datastore $datastore | ForEach-Object { $_.ExtensionData.MoRef } $vms = (Get-Cluster -name $cluster | get-vm | Where-Object { $_.PowerState -EQ "PoweredOn" }) | Where-Object { $vm = $_; $datastoreID | Where-Object { $vm.DatastoreIdList -contains $_ } } if ($vms) { - Write-PowerManagementLogMessage -Type INFO -Message "Remote VMs with names $vms are running on cluster '$cluster' and datastore '$datastore.' `n" + Write-LogMessage -Type INFO -Message "Remote VMs with names $vms are running on cluster '$cluster' and datastore '$datastore.' `n" [Array]$PoweredOnVMs += $vms } } @@ -863,15 +863,15 @@ Function Get-poweronVMsOnRemoteDS { } return $PoweredOnVMs } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-poweronVMsOnRemoteDS cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Get-poweronVMsOnRemoteDS cmdlet." } } Export-ModuleMember -Function Get-poweronVMsOnRemoteDS @@ -911,11 +911,11 @@ Function Test-LockdownMode { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Test-LockdownMode cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Test-LockdownMode cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } @@ -926,42 +926,42 @@ Function Test-LockdownMode { $hostsWithLockdown = "" if ($hostsInCluster.count -ne 0) { foreach ($esxiHost in $hostsInCluster) { - Write-PowerManagementLogMessage -Type INFO -Message "Checking lockdown mode for $esxiHost ...." + Write-LogMessage -Type INFO -Message "Checking lockdown mode for $esxiHost ...." $lockdownStatus = (Get-VMHost -Name $esxiHost).ExtensionData.Config.LockdownMode if ($lockdownStatus -EQ $null) { $checkServer = (Test-EndpointConnection -server $esxiHost -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot fetch information about lockdown mode for ESXi host $esxiHost!" + Write-LogMessage -Type ERROR -Message "Cannot fetch information about lockdown mode for ESXi host $esxiHost!" } else { - Write-PowerManagementLogMessage -Type WARNING -Message "Cannot fetch information about lockdown mode. Host $esxiHost is not reachable." - Write-PowerManagementLogMessage -Type ERROR -Message "Check the status on the ESXi host $esxiHost!" + Write-LogMessage -Type WARNING -Message "Cannot fetch information about lockdown mode. Host $esxiHost is not reachable." + Write-LogMessage -Type ERROR -Message "Check the status on the ESXi host $esxiHost!" } } else { if ($lockdownStatus -ne "lockdownDisabled") { - Write-PowerManagementLogMessage -Type WARNING -Message "Lockdown mode is enabled for ESXi host $esxiHost" + Write-LogMessage -Type WARNING -Message "Lockdown mode is enabled for ESXi host $esxiHost" $hostsWithLockdown += ", $esxiHost" } } } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cluster $cluster is not present on server $server. Check the input to the cmdlet." + Write-LogMessage -Type ERROR -Message "Cluster $cluster is not present on server $server. Check the input to the cmdlet." } if ([string]::IsNullOrEmpty($hostsWithLockdown)) { - Write-PowerManagementLogMessage -Type INFO -Message "Cluster $cluster does not have ESXi hosts in lockdown mode." + Write-LogMessage -Type INFO -Message "Cluster $cluster does not have ESXi hosts in lockdown mode." } else { - Write-PowerManagementLogMessage -Type INFO -Message "The following ESXi hosts are in lockdown mode: $hostsWithLockdown. Disable lockdown mode to continue." - Write-PowerManagementLogMessage -Type ERROR -Message "Some hosts are in lockdown mode. Disable lockdown mode to continue." + Write-LogMessage -Type INFO -Message "The following ESXi hosts are in lockdown mode: $hostsWithLockdown. Disable lockdown mode to continue." + Write-LogMessage -Type ERROR -Message "Some hosts are in lockdown mode. Disable lockdown mode to continue." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again." } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Test-LockdownMode cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Test-LockdownMode cmdlet." } } Export-ModuleMember -Function Test-LockdownMode @@ -1005,43 +1005,43 @@ Function Get-VMRunningStatus { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-VMRunningStatus cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Get-VMRunningStatus cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null if ($DefaultVIServer.Name -EQ $server) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to host '$server' and checking if nodes named '$pattern' are in the '$($status.ToUpper())' state..." + Write-LogMessage -Type INFO -Message "Connected to host '$server' and checking if nodes named '$pattern' are in the '$($status.ToUpper())' state..." $nodes = Get-VM | Where-Object Name -Match $pattern | Select-Object Name, PowerState, VMHost if ($nodes.Name.Count -EQ 0) { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot find nodes matching pattern '$pattern' in the inventory of host '$server'." + Write-LogMessage -Type ERROR -Message "Cannot find nodes matching pattern '$pattern' in the inventory of host '$server'." } else { foreach ($node in $nodes) { $vmObject = Get-VMGuest -server $server -VM $node.Name -ErrorAction SilentlyContinue | Where-Object VmUid -Match $server if ($vmObject.State -EQ $status) { - Write-PowerManagementLogMessage -Type INFO -Message "Node $($node.Name) is in '$($status.ToUpper()) state.'" + Write-LogMessage -Type INFO -Message "Node $($node.Name) is in '$($status.ToUpper()) state.'" return $true } else { - Write-PowerManagementLogMessage -Type INFO -Message "Node $($node.Name) is not in '$($status.ToUpper()) state'." + Write-LogMessage -Type INFO -Message "Node $($node.Name) is not in '$($status.ToUpper()) state'." return $false } } } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-VMRunningStatus cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Get-VMRunningStatus cmdlet." } } Export-ModuleMember -Function Get-VMRunningStatus @@ -1085,33 +1085,33 @@ Function Invoke-EsxCommand { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Invoke-EsxCommand cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Invoke-EsxCommand cmdlet." $password = ConvertTo-SecureString $pass -AsPlainText -Force $Cred = New-Object System.Management.Automation.PSCredential ($user, $password) - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." $session = New-SSHSession -ComputerName $server -Credential $Cred -Force -WarningAction SilentlyContinue if ($session) { - Write-PowerManagementLogMessage -Type INFO -Message "Attempting to run command '$cmd' on server '$server'..." + Write-LogMessage -Type INFO -Message "Attempting to run command '$cmd' on server '$server'..." $commandOutput = Invoke-SSHCommand -Index $session.SessionId -Command $cmd -Timeout 900 if ($expected ) { if (($commandOutput.Output -match $expected)) { - Write-PowerManagementLogMessage -Type INFO -Message "Command '$cmd' completed with expected output on server '$server'." + Write-LogMessage -Type INFO -Message "Command '$cmd' completed with expected output on server '$server'." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Failure. The `"$($expected)`" is not present in `"$($commandOutput.Output)`" output" + Write-LogMessage -Type ERROR -Message "Failure. The `"$($expected)`" is not present in `"$($commandOutput.Output)`" output" } } elseif ($commandOutput.exitStatus -EQ 0) { - Write-PowerManagementLogMessage -Type INFO -Message "Success. The command completed successfully." + Write-LogMessage -Type INFO -Message "Success. The command completed successfully." } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Failure. The command could not be run." + Write-LogMessage -Type ERROR -Message "Failure. The command could not be run." } Remove-SSHSession -Index $session.SessionId | Out-Null } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Invoke-EsxCommand cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Invoke-EsxCommand cmdlet." } } Export-ModuleMember -Function Invoke-EsxCommand @@ -1147,28 +1147,28 @@ Function Get-SSHEnabledStatus { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-SSHEnabledStatus cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Get-SSHEnabledStatus cmdlet." $password = ConvertTo-SecureString $pass -AsPlainText -Force $Cred = New-Object System.Management.Automation.PSCredential ($user, $password) $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Attempting to open an SSH connection to server '$server'..." + Write-LogMessage -Type INFO -Message "Attempting to open an SSH connection to server '$server'..." $session = New-SSHSession -ComputerName $server -Credential $Cred -Force -WarningAction SilentlyContinue -ErrorAction SilentlyContinue if ($session) { - Write-PowerManagementLogMessage -Type INFO -Message "SSH is enabled on '$server'." + Write-LogMessage -Type INFO -Message "SSH is enabled on '$server'." Remove-SSHSession -Index $session.SessionId | Out-Null return $True } else { - Write-PowerManagementLogMessage -Type INFO -Message "SSH is not enabled '$server'." + Write-LogMessage -Type INFO -Message "SSH is not enabled '$server'." return $False } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot communicate with server '$server'. Check the power state of the server." + Write-LogMessage -Type ERROR -Message "Cannot communicate with server '$server'. Check the power state of the server." } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-SSHEnabledStatus cmdlet" + Write-LogMessage -Type INFO -Message "Completed the call to the Get-SSHEnabledStatus cmdlet" } } Export-ModuleMember -Function Get-SSHEnabledStatus @@ -1208,16 +1208,16 @@ Function Test-VsanHealth { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Test-VsanHealth cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Test-VsanHealth cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null if ($DefaultVIServer.Name -EQ $server) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server' and attempting to check the vSAN cluster health..." + Write-LogMessage -Type INFO -Message "Connected to server '$server' and attempting to check the vSAN cluster health..." $count = 1 $flag = 0 While ($count -lt 5) { @@ -1229,14 +1229,14 @@ Function Test-VsanHealth { Break } } Catch { - Write-PowerManagementLogMessage -Type INFO -Message "The vSAN health service is yet to come up, please wait ..." + Write-LogMessage -Type INFO -Message "The vSAN health service is yet to come up, please wait ..." Start-Sleep -s 60 $count += 1 } } if (-Not $flag) { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot run the Test-VsanHealth cmdlet because the vSAN health service is not running." + Write-LogMessage -Type ERROR -Message "Cannot run the Test-VsanHealth cmdlet because the vSAN health service is not running." } else { Start-Sleep -s 60 $vchs = Get-VSANView -Server $server -Id "VsanVcClusterHealthSystem-vsan-cluster-health-system" @@ -1262,24 +1262,24 @@ Function Test-VsanHealth { $healthCheckResults += $healthCheckGroupResult } if ($health_status -EQ 'GREEN' -and $results.OverallHealth -ne 'red') { - Write-PowerManagementLogMessage -Type INFO -Message "The vSAN health status for $cluster is good." + Write-LogMessage -Type INFO -Message "The vSAN health status for $cluster is good." return 0 } else { - Write-PowerManagementLogMessage -Type ERROR -Message "The vSAN health status for $cluster is bad." + Write-LogMessage -Type ERROR -Message "The vSAN health status for $cluster is bad." return 1 } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Test-VsanHealth cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Test-VsanHealth cmdlet." } } Export-ModuleMember -Function Test-VsanHealth @@ -1319,36 +1319,36 @@ Function Test-VsanObjectResync { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Test-VsanObjectResync cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Test-VsanObjectResync cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null if ($DefaultVIServer.Name -EQ $server) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server' and attempting to check the resynchronization status... " + Write-LogMessage -Type INFO -Message "Connected to server '$server' and attempting to check the resynchronization status... " $noResyncingObjects = Get-VsanResyncingComponent -Server $server -cluster $cluster -ErrorAction Ignore - Write-PowerManagementLogMessage -Type INFO -Message "Number of resynchronizing objects: $noResyncingObjects." + Write-LogMessage -Type INFO -Message "Number of resynchronizing objects: $noResyncingObjects." if ($noResyncingObjects.count -EQ 0) { - Write-PowerManagementLogMessage -Type INFO -Message "No resynchronizing objects." + Write-LogMessage -Type INFO -Message "No resynchronizing objects." return 0 } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Resynchronizing objects in progress..." + Write-LogMessage -Type ERROR -Message "Resynchronizing objects in progress..." return 1 } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Test-VsanObjectResync cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Test-VsanObjectResync cmdlet." } } Export-ModuleMember -Function Test-VsanObjectResync @@ -1411,16 +1411,16 @@ Function Get-VMsWithPowerStatus { Try { - if (-Not $silence) { Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-VMsWithPowerStatus cmdlet." } + if (-Not $silence) { Write-LogMessage -Type INFO -Message "Starting the call to the Get-VMsWithPowerStatus cmdlet." } $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - if (-Not $silence) { Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." } + if (-Not $silence) { Write-LogMessage -Type INFO -Message "Connecting to '$server'..." } if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null if ($DefaultVIServer.Name -EQ $server) { - if (-Not $silence) { Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server' and attempting to get the list of virtual machines..." } + if (-Not $silence) { Write-LogMessage -Type INFO -Message "Connected to server '$server' and attempting to get the list of virtual machines..." } if ($pattern) { if ($PSBoundParameters.ContainsKey('exactMatch') ) { $noOfVMs = get-vm -Server $server | Where-Object Name -EQ $pattern | Where-Object PowerState -EQ $powerState @@ -1431,23 +1431,23 @@ Function Get-VMsWithPowerStatus { $noOfVMs = get-vm -Server $server | Where-Object PowerState -EQ $powerState } if ($noOfVMs.count -EQ 0) { - if (-Not $silence) { Write-PowerManagementLogMessage -Type INFO -Message "No virtual machines in the $powerState state." } + if (-Not $silence) { Write-LogMessage -Type INFO -Message "No virtual machines in the $powerState state." } } else { $noOfVMsString = $noOfVMs -join "," - if (-Not $silence) { Write-PowerManagementLogMessage -Type INFO -Message "The virtual machines in the $powerState state are: $noOfVMsString" } + if (-Not $silence) { Write-LogMessage -Type INFO -Message "The virtual machines in the $powerState state are: $noOfVMsString" } } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null Return $noOfVMs } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - if (-Not $silence) { Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-VMsWithPowerStatus cmdlet." } + if (-Not $silence) { Write-LogMessage -Type INFO -Message "Completed the call to the Get-VMsWithPowerStatus cmdlet." } } } Export-ModuleMember -Function Get-VMsWithPowerStatus @@ -1495,12 +1495,12 @@ Function Get-VamiServiceStatus { Try { if (-Not $nolog) { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-VAMIServiceStatus cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Get-VAMIServiceStatus cmdlet." } $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { if (-Not $nolog) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." } if ($DefaultCisServers) { Disconnect-CisServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null @@ -1516,7 +1516,7 @@ Function Get-VamiServiceStatus { Start-Sleep -s 60 $retries -= 1 if (-Not $nolog) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to the vSphere Automation API endpoint might take some time. Please wait." + Write-LogMessage -Type INFO -Message "Connecting to the vSphere Automation API endpoint might take some time. Please wait." } } if ($flag) { @@ -1524,17 +1524,17 @@ Function Get-VamiServiceStatus { $serviceStatus = $vMonAPI.Get($service, 0) return $serviceStatus.state } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Testing the connection to server '$server' has failed. Check your details and try again." + Write-LogMessage -Type ERROR -Message "Testing the connection to server '$server' has failed. Check your details and try again." } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { Disconnect-CisServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null if (-Not $nolog) { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-VAMIServiceStatus cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Get-VAMIServiceStatus cmdlet." } } } @@ -1588,13 +1588,13 @@ Function Set-VamiServiceStatus { Try { if (-Not $nolog) { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Set-VamiServiceStatus cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Set-VamiServiceStatus cmdlet." } # TODO check if 443 is the default communication port $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { if (-Not $nolog) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." } if ($DefaultCisServers) { Disconnect-CisServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null @@ -1610,7 +1610,7 @@ Function Set-VamiServiceStatus { Start-Sleep -s 60 $retries -= 1 if (-Not $nolog) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to the vSphere Automation API endpoint might take some time. Please wait." + Write-LogMessage -Type INFO -Message "Connecting to the vSphere Automation API endpoint might take some time. Please wait." } } if ($flag) { @@ -1620,44 +1620,44 @@ Function Set-VamiServiceStatus { $serviceStatus = $vMonAPI.Get($service, 0) if ($serviceStatus.state -EQ "STARTED") { if (-Not $nolog) { - Write-PowerManagementLogMessage -Type INFO -Message "Service '$service' is successfully started." + Write-LogMessage -Type INFO -Message "Service '$service' is successfully started." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Could not start service '$service'." + Write-LogMessage -Type ERROR -Message "Could not start service '$service'." } } elseif ($state -EQ "stop") { $vMonAPI.Stop($service) $serviceStatus = $vMonAPI.Get($service, 0) if ($serviceStatus.state -EQ "STOPPED") { if (-Not $nolog) { - Write-PowerManagementLogMessage -Type INFO -Message "Service '$service' is successfully stopped." + Write-LogMessage -Type INFO -Message "Service '$service' is successfully stopped." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Could not stop service '$service'." + Write-LogMessage -Type ERROR -Message "Could not stop service '$service'." } } else { $vMonAPI.ReStart($service) $serviceStatus = $vMonAPI.Get($service, 0) if ($serviceStatus.state -EQ "STARTED") { if (-Not $nolog) { - Write-PowerManagementLogMessage -Type INFO -Message "Service '$service' is successfully restarted." + Write-LogMessage -Type INFO -Message "Service '$service' is successfully restarted." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Could not restart service '$service'." + Write-LogMessage -Type ERROR -Message "Could not restart service '$service'." } } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Testing the connection to server '$server' has failed. Check your details and try again." + Write-LogMessage -Type ERROR -Message "Testing the connection to server '$server' has failed. Check your details and try again." } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { Disconnect-CisServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null if (-Not $nolog) { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Set-VamiServiceStatus cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Set-VamiServiceStatus cmdlet." } } } @@ -1709,30 +1709,30 @@ Function Set-VsphereHA { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Set-VsphereHA cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Set-VsphereHA cmdlet." if ($(Test-EndpointConnection -server $server -Port 443)) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null if ($DefaultVIServer.Name -EQ $server) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server'... ..." + Write-LogMessage -Type INFO -Message "Connected to server '$server'... ..." $retryCount = 0 $completed = $false $SecondsDelay = 10 $Retries = 60 if ($enableHA) { if ($(get-cluster -Name $cluster).HAEnabled) { - Write-PowerManagementLogMessage -Type INFO -Message "vSphere High Availability is already enabled on the vSAN cluster. " + Write-LogMessage -Type INFO -Message "vSphere High Availability is already enabled on the vSAN cluster. " return $true } else { - Write-PowerManagementLogMessage -Type INFO -Message "Enabling vSphere High Availability for cluster '$cluster'..." + Write-LogMessage -Type INFO -Message "Enabling vSphere High Availability for cluster '$cluster'..." Set-Cluster -Server $server -Cluster $cluster -HAEnabled:$true -Confirm:$false | Out-Null While (-Not $completed) { # Check iteration number if ($retrycount -ge $Retries) { - Write-PowerManagementLogMessage -Type WARNING -Message "Set vSphere High Availability timeouted after $($SecondsDelay * $Retries) seconds. There are still reconfiguratons in progress." + Write-LogMessage -Type WARNING -Message "Set vSphere High Availability timeouted after $($SecondsDelay * $Retries) seconds. There are still reconfiguratons in progress." return $false } $retryCount++ @@ -1740,16 +1740,16 @@ Function Set-VsphereHA { Start-Sleep -s 5 $runningTasks = get-task -Status Running if (($runningTasks -match "Update vSAN configuration") -or ($runningTasks -match "Configuring vSphere HA")) { - Write-PowerManagementLogMessage -Type INFO -Message "vSphere High Availability configuration changes are not applied. Sleeping for $SecondsDelay seconds..." + Write-LogMessage -Type INFO -Message "vSphere High Availability configuration changes are not applied. Sleeping for $SecondsDelay seconds..." Start-Sleep -s $SecondsDelay continue } else { $completed = $true if ($(get-cluster -Name $cluster).HAEnabled) { - Write-PowerManagementLogMessage -Type INFO -Message "vSphere High Availability for cluster '$cluster' changed to 'Enabled'." + Write-LogMessage -Type INFO -Message "vSphere High Availability for cluster '$cluster' changed to 'Enabled'." return $true } else { - Write-PowerManagementLogMessage -Type WARNING -Message "Failed to set vSphere High Availability for cluster '$cluster' to 'Enabled'." + Write-LogMessage -Type WARNING -Message "Failed to set vSphere High Availability for cluster '$cluster' to 'Enabled'." return $false } } @@ -1758,15 +1758,15 @@ Function Set-VsphereHA { } if ($disableHA) { if (!$(get-cluster -Name $cluster).HAEnabled) { - Write-PowerManagementLogMessage -Type INFO -Message "vSphere High Availability is already disabled on the vSAN cluster. " + Write-LogMessage -Type INFO -Message "vSphere High Availability is already disabled on the vSAN cluster. " return $true } else { - Write-PowerManagementLogMessage -Type INFO -Message "Disabling vSphere High Availability for cluster '$cluster'." + Write-LogMessage -Type INFO -Message "Disabling vSphere High Availability for cluster '$cluster'." Set-Cluster -Server $server -Cluster $cluster -HAEnabled:$false -Confirm:$false | Out-Null While (-Not $completed) { # Check iteration number if ($retrycount -ge $Retries) { - Write-PowerManagementLogMessage -Type WARNING -Message "Set vSphere High Availability timeouted after $($SecondsDelay * $Retries) seconds. There are still reconfiguratons in progress." + Write-LogMessage -Type WARNING -Message "Set vSphere High Availability timeouted after $($SecondsDelay * $Retries) seconds. There are still reconfiguratons in progress." return $false } $retryCount++ @@ -1774,16 +1774,16 @@ Function Set-VsphereHA { Start-Sleep -s 5 $runningTasks = get-task -Status Running if (($runningTasks -match "Update vSAN configuration") -or ($runningTasks -match "Configuring vSphere HA")) { - Write-PowerManagementLogMessage -Type INFO -Message "vSphere High Availability configuration changes are not applied. Sleeping for $SecondsDelay seconds..." + Write-LogMessage -Type INFO -Message "vSphere High Availability configuration changes are not applied. Sleeping for $SecondsDelay seconds..." Start-Sleep -s $SecondsDelay continue } else { $completed = $true if (!$(get-cluster -Name $cluster).HAEnabled) { - Write-PowerManagementLogMessage -Type INFO -Message "Disabled vSphere High Availability for cluster '$cluster'." + Write-LogMessage -Type INFO -Message "Disabled vSphere High Availability for cluster '$cluster'." return $true } else { - Write-PowerManagementLogMessage -Type WARNING -Message "Failed to disable vSphere High Availability for cluster '$cluster'." + Write-LogMessage -Type WARNING -Message "Failed to disable vSphere High Availability for cluster '$cluster'." return $false } } @@ -1791,15 +1791,15 @@ Function Set-VsphereHA { } } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again." } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Set-VsphereHA cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Set-VsphereHA cmdlet." } } @@ -1840,35 +1840,35 @@ Function Get-DrsAutomationLevel { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-DrsAutomationLevel cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Get-DrsAutomationLevel cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null if ($DefaultVIServer.Name -EQ $server) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server'... ..." + Write-LogMessage -Type INFO -Message "Connected to server '$server'... ..." $ClusterData = Get-Cluster -Name $cluster if ($ClusterData.DrsEnabled) { $clsdrsvalue = $ClusterData.DrsAutomationLevel - Write-PowerManagementLogMessage -Type INFO -Message "The cluster DRS value: $clsdrsvalue." + Write-LogMessage -Type INFO -Message "The cluster DRS value: $clsdrsvalue." } else { - Write-PowerManagementLogMessage -Type INFO -Message "vSphere DRS is not enabled on the cluster $cluster." + Write-LogMessage -Type INFO -Message "vSphere DRS is not enabled on the cluster $cluster." } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null return $clsdrsvalue } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-DrsAutomationLevel cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Get-DrsAutomationLevel cmdlet." } } @@ -1917,49 +1917,49 @@ Function Set-Retreatmode { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Set-Retreatmode cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Set-Retreatmode cmdlet." $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null if ($DefaultVIServer.Name -EQ $server) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server'..." + Write-LogMessage -Type INFO -Message "Connected to server '$server'..." $cluster_id = Get-Cluster -Name $cluster | Select-Object -Property Id $domainOut = $cluster_id.Id -match 'domain-c.*' $domain_id = $Matches[0] $advanced_setting = "config.vcls.clusters.$domain_id.enabled" if (Get-AdvancedSetting -Entity $server -Name $advanced_setting) { - Write-PowerManagementLogMessage -Type INFO -Message "Advanced setting $advanced_setting is present." + Write-LogMessage -Type INFO -Message "Advanced setting $advanced_setting is present." if ($mode -EQ 'enable') { Get-AdvancedSetting -Entity $server -Name $advanced_setting | Set-AdvancedSetting -Value 'false' -Confirm:$false | Out-Null - Write-PowerManagementLogMessage -Type INFO -Message "Advanced setting $advanced_setting is set to false." + Write-LogMessage -Type INFO -Message "Advanced setting $advanced_setting is set to false." } else { Get-AdvancedSetting -Entity $server -Name $advanced_setting | Set-AdvancedSetting -Value 'true' -Confirm:$false | Out-Null - Write-PowerManagementLogMessage -Type INFO -Message "Advanced setting $advanced_setting is set to true." + Write-LogMessage -Type INFO -Message "Advanced setting $advanced_setting is set to true." } } else { if ($mode -EQ 'enable') { New-AdvancedSetting -Entity $server -Name $advanced_setting -Value 'false' -Confirm:$false | Out-Null - Write-PowerManagementLogMessage -Type INFO -Message "Advanced setting $advanced_setting is set to false." + Write-LogMessage -Type INFO -Message "Advanced setting $advanced_setting is set to false." } else { New-AdvancedSetting -Entity $server -Name $advanced_setting -Value 'true' -Confirm:$false | Out-Null - Write-PowerManagementLogMessage -Type INFO -Message "Advanced setting $advanced_setting is set to true." + Write-LogMessage -Type INFO -Message "Advanced setting $advanced_setting is set to true." } } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Set-Retreatmode cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Set-Retreatmode cmdlet." } } @@ -2017,16 +2017,16 @@ Function Get-VMToClusterMapping { $pass = Get-Password -User $user -Password $pass Try { - if (-Not $silence) { Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-VMToClusterMapping cmdlet." } + if (-Not $silence) { Write-LogMessage -Type INFO -Message "Starting the call to the Get-VMToClusterMapping cmdlet." } $checkServer = (Test-EndpointConnection -server $server -Port 443) if ($checkServer) { - if (-Not $silence) { Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." } + if (-Not $silence) { Write-LogMessage -Type INFO -Message "Connecting to '$server'..." } if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null if ($DefaultVIServer.Name -EQ $server) { - if (-Not $silence) { Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server'..." } + if (-Not $silence) { Write-LogMessage -Type INFO -Message "Connected to server '$server'..." } foreach ($clus in $cluster) { if ($powerState) { $VMs += get-vm -location $clus | Where-Object { (Get-VM -location $folder) -contains $_ } | Where-Object PowerState -EQ $powerState @@ -2035,20 +2035,20 @@ Function Get-VMToClusterMapping { } } $clustersstring = $cluster -join "," - if (-Not $silence) { Write-PowerManagementLogMessage -Type INFO -Message "The list of VMs on cluster $clustersstring is $VMs" } + if (-Not $silence) { Write-LogMessage -Type INFO -Message "The list of VMs on cluster $clustersstring is $VMs" } Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null return $VMs } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - if (-Not $silence) { Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-VMToClusterMapping cmdlet." } + if (-Not $silence) { Write-LogMessage -Type INFO -Message "Completed the call to the Get-VMToClusterMapping cmdlet." } } } @@ -2085,8 +2085,8 @@ Function Wait-ForStableNsxtClusterStatus { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Wait-ForStableNsxtClusterStatus cmdlet." - Write-PowerManagementLogMessage -Type INFO -Message "Waiting the cluster to become 'STABLE' for NSX Manager '$server'... This could take up to 20 min." + Write-LogMessage -Type INFO -Message "Starting the call to the Wait-ForStableNsxtClusterStatus cmdlet." + Write-LogMessage -Type INFO -Message "Waiting the cluster to become 'STABLE' for NSX Manager '$server'... This could take up to 20 min." # Create NSX-T header $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass))) # Create Basic Authentication Encoded Credentials $headers = @{"Accept" = "application/json" } @@ -2102,7 +2102,7 @@ Function Wait-ForStableNsxtClusterStatus { While (-Not $completed) { # Check iteration number if ($retrycount -ge $Retries) { - Write-PowerManagementLogMessage -Type WARNING -Message "Request to '$uri' failed after $retryCount attempts." + Write-LogMessage -Type WARNING -Message "Request to '$uri' failed after $retryCount attempts." return $false } $retryCount++ @@ -2110,31 +2110,31 @@ Function Wait-ForStableNsxtClusterStatus { Try { $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $headers -ContentType application/json -TimeoutSec 60 } Catch { - Write-PowerManagementLogMessage -Type INFO -Message "Could not connect to NSX Manager '$server'! Sleeping $($SecondsDelay * $aditionalWaitMultiplier) seconds before next attempt." + Write-LogMessage -Type INFO -Message "Could not connect to NSX Manager '$server'! Sleeping $($SecondsDelay * $aditionalWaitMultiplier) seconds before next attempt." Start-Sleep -s $($SecondsDelay * $aditionalWaitMultiplier) continue } $successfulConnections++ if ($response.mgmt_cluster_status.status -ne 'STABLE') { - Write-PowerManagementLogMessage -Type INFO -Message "Expecting NSX Manager cluster state 'STABLE', present state: $($response.mgmt_cluster_status.status)" + Write-LogMessage -Type INFO -Message "Expecting NSX Manager cluster state 'STABLE', present state: $($response.mgmt_cluster_status.status)" # Add longer sleep during fiest several attempts to avoid locking the NSX-T account just after power-on if ($successfulConnections -lt 4) { - Write-PowerManagementLogMessage -Type INFO -Message "Sleeping for $($SecondsDelay * $aditionalWaitMultiplier) seconds before next check..." + Write-LogMessage -Type INFO -Message "Sleeping for $($SecondsDelay * $aditionalWaitMultiplier) seconds before next check..." Start-Sleep -s $($SecondsDelay * $aditionalWaitMultiplier) } else { - Write-PowerManagementLogMessage -Type INFO -Message "Sleeping for $SecondsDelay seconds until the next check..." + Write-LogMessage -Type INFO -Message "Sleeping for $SecondsDelay seconds until the next check..." Start-Sleep -s $SecondsDelay } } else { $completed = $true - Write-PowerManagementLogMessage -Type INFO -Message "The state of the NSX Manager cluster '$server' is 'STABLE'." + Write-LogMessage -Type INFO -Message "The state of the NSX Manager cluster '$server' is 'STABLE'." return $true } } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Wait-ForStableNsxtClusterStatus cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Wait-ForStableNsxtClusterStatus cmdlet." } } Export-ModuleMember -Function Wait-ForStableNsxtClusterStatus @@ -2178,16 +2178,16 @@ Function Get-EdgeNodeFromNSXManager { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-EdgeNodeFromNSXManager cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Get-EdgeNodeFromNSXManager cmdlet." if ( Test-EndpointConnection -server $server -Port 443 ) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultNSXTServers) { Disconnect-NSXTServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-NsxTServer -server $server -user $user -password $pass | Out-Null $edge_nodes_list = @() if ($DefaultNsxTServers.Name -EQ $server) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server'..." + Write-LogMessage -Type INFO -Message "Connected to server '$server'..." #get transport nodes info $transport_nodes_var = Get-NSXtService com.vmware.nsx.transport_nodes $transport_nodes_list = $transport_nodes_var.list().results @@ -2209,15 +2209,15 @@ Function Get-EdgeNodeFromNSXManager { Disconnect-NSXTServer * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null return $edge_nodes_list } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check the console output for more details." + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check the console output for more details." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-EdgeNodeFromNSXManager cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Get-EdgeNodeFromNSXManager cmdlet." } } Export-ModuleMember -Function Get-EdgeNodeFromNSXManager @@ -2253,30 +2253,30 @@ Function Get-NSXTComputeManagers { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-NSXTComputeManagers cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Get-NSXTComputeManagers cmdlet." if ( Test-EndpointConnection -server $server -Port 443 ) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultNSXTServers) { Disconnect-NSXTServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } Connect-NsxTServer -server $server -user $user -password $pass | Out-Null if ($DefaultNsxTServers.Name -EQ $server) { - Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server'..." + Write-LogMessage -Type INFO -Message "Connected to server '$server'..." # Get compute managers info $compute_manager_var = Get-NsXtService com.vmware.nsx.fabric.compute_managers $compute_manager_list = $compute_manager_var.list().results.server Disconnect-NSXTServer * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null return $compute_manager_list } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check the console output for more details." + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check the console output for more details." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again." + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again." } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-NSXTComputeManagers cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Get-NSXTComputeManagers cmdlet." } } Export-ModuleMember -Function Get-NSXTComputeManagers @@ -2316,9 +2316,9 @@ Function Get-TanzuEnabledClusterStatus { $pass = Get-Password -User $user -Password $pass Try { - Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-TanzuEnabledClusterStatus cmdlet." + Write-LogMessage -Type INFO -Message "Starting the call to the Get-TanzuEnabledClusterStatus cmdlet." if ( Test-EndpointConnection -server $server -Port 443 ) { - Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..." + Write-LogMessage -Type INFO -Message "Connecting to '$server'..." if ($DefaultVIServers) { Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null } @@ -2326,52 +2326,53 @@ Function Get-TanzuEnabledClusterStatus { if ($DefaultVIServer.Name -EQ $server) { $out = get-wmcluster -cluster $cluster -server $server -ErrorVariable ErrorMsg -ErrorAction SilentlyContinue if ($out.count -gt 0) { - Write-PowerManagementLogMessage -Type INFO -Message "vSphere with Tanzu is enabled." + Write-LogMessage -Type INFO -Message "vSphere with Tanzu is enabled." return $True } elseif (([string]$ErrorMsg -match "does not have Workloads enabled") -or ([string]::IsNullOrEmpty($ErrorMsg))) { - Write-PowerManagementLogMessage -Type INFO -Message "vSphere with Tanzu is not enabled." + Write-LogMessage -Type INFO -Message "vSphere with Tanzu is not enabled." return $False } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Cannot fetch information related to vSphere with Tanzu. ERROR message from 'get-wmcluster' command: '$ErrorMsg'" + Write-LogMessage -Type ERROR -Message "Cannot fetch information related to vSphere with Tanzu. ERROR message from 'get-wmcluster' command: '$ErrorMsg'" } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check the console output for more details." + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check the console output for more details." } } else { - Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" + Write-LogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again" } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } Finally { - Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-TanzuEnabledClusterStatus cmdlet." + Write-LogMessage -Type INFO -Message "Completed the call to the Get-TanzuEnabledClusterStatus cmdlet." } } Export-ModuleMember -Function Get-TanzuEnabledClusterStatus -######### Start Useful Script Functions ########## -Function Write-PowerManagementLogMessage { +######### Start Internal Helper Functions ########## + +Function Write-LogMessage { <# .SYNOPSIS - This cmdlet is used for logging messages. + Used for logging messages. .DESCRIPTION - This cmdlet is used for logging messages on the console. + Used for logging messages on the console. .EXAMPLE - Write-PowerManagementLogMessage -Type ERROR -message "Error message" + Write-LogMessage -Type ERROR -message "Error message" Logs as a error message and uses the assigned color. - Write-PowerManagementLogMessage -Type WARNING -message "Warning message" + Write-LogMessage -Type WARNING -message "Warning message" Logs as a warning message and uses the assigned color. - Write-PowerManagementLogMessage -Type INFO -message "Info message" + Write-LogMessage -Type INFO -message "Info message" Logs as a info message and uses the assigned color. - Write-PowerManagementLogMessage -Type EXCEPTION -message "Exception message" + Write-LogMessage -Type EXCEPTION -message "Exception message" Logs as an exception message and uses the assigned color. - Write-PowerManagementLogMessage -Type INFO -message "Exception message" -colour Cyan + Write-LogMessage -Type INFO -message "Exception message" -colour Cyan Logs as an exception message and uses the the specified color. .PARAMETER Message @@ -2430,9 +2431,8 @@ Function Write-PowerManagementLogMessage { $logContent = '[' + $timeStamp + '] ' + $type + ' ' + $message Add-Content -Path $logFile $logContent } -Export-ModuleMember -Function Write-PowerManagementLogMessage -Function Debug-CatchWriterForPowerManagement { +Function Write-DebugMessage { Param ( [Parameter (Mandatory = $true)] [PSObject]$object ) @@ -2440,9 +2440,9 @@ Function Debug-CatchWriterForPowerManagement { $lineNumber = $object.InvocationInfo.ScriptLineNumber $lineText = $object.InvocationInfo.Line.trim() $errorMessage = $object.Exception.Message - Write-PowerManagementLogMessage -Message " ERROR at Script Line $lineNumber" -Colour Red - Write-PowerManagementLogMessage -Message " Relevant Command: $lineText" -Colour Red - Write-PowerManagementLogMessage -Message " ERROR Message: $errorMessage" -Colour Red + Write-LogMessage -Message " ERROR at Script Line $lineNumber" -Colour Red + Write-LogMessage -Message " Relevant Command: $lineText" -Colour Red + Write-LogMessage -Message " ERROR Message: $errorMessage" -Colour Red Write-Error -Message $errorMessage }