From 1ede01eb5878ca1fa822c78cb77ea14fdc739f5e 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 | 444 ++++++++------ .../PowerManagement-WorkloadDomain.ps1 | 72 ++- VMware.CloudFoundation.PowerManagement.psm1 | 580 +++++++++--------- 3 files changed, 607 insertions(+), 489 deletions(-) diff --git a/SampleScripts/PowerManagement-ManagementDomain.ps1 b/SampleScripts/PowerManagement-ManagementDomain.ps1 index c4c7eef..6b3665e 100644 --- a/SampleScripts/PowerManagement-ManagementDomain.ps1 +++ b/SampleScripts/PowerManagement-ManagementDomain.ps1 @@ -74,13 +74,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 ) @@ -88,9 +148,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 } @@ -98,7 +158,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" } @@ -108,36 +168,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 @@ -149,11 +209,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 } @@ -165,25 +225,25 @@ $sddcManagerPassword = $pass 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) { @@ -192,10 +252,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" } @@ -222,49 +282,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 @@ -274,7 +334,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) @@ -282,34 +342,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) @@ -317,12 +377,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 @@ -331,15 +391,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 @@ -355,13 +415,12 @@ 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 } } $cluster = Get-VCFCluster | Where-Object { $_.id -eq ($workloadDomain.clusters.id) } - >>>(bug:Missing command) $var = @{} $var["Domain"] = @{} $var["Domain"]["name"] = $workloadDomain.name @@ -370,7 +429,6 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe $var["Cluster"] = @{} $var["Cluster"]["name"] = $cluster.name - # Check the SDDC Manager version if VCF less than or greater than VCF 5.0 if ([float]$vcfVersion -lt [float]5.0) { # Gather vCenter Server Details and Credentials @@ -386,14 +444,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 } @@ -480,16 +538,16 @@ 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-Output "adminpssword: $nsxtManagerVIP.adminPassword" - 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!" } } @@ -509,7 +567,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 +602,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 +625,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 +644,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 } } @@ -609,10 +667,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." } } } @@ -623,17 +681,17 @@ 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)..." + 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 @@ -641,10 +699,10 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe $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 @@ -655,12 +713,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 @@ -669,7 +727,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 @@ -678,8 +736,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 } } @@ -687,15 +745,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 } } @@ -713,7 +771,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 } } @@ -747,17 +805,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..." } } } @@ -769,23 +827,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 } @@ -797,14 +855,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 { @@ -812,7 +870,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 } @@ -820,7 +878,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 @@ -831,24 +889,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 } @@ -856,20 +914,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 = @() @@ -883,15 +941,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 { @@ -902,24 +960,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 @@ -930,15 +988,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. 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 @@ -948,7 +1006,7 @@ if ($PsBoundParameters.ContainsKey("shutdown") -or $PsBoundParameters.ContainsKe } } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ Exit } } @@ -958,7 +1016,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 @@ -1032,29 +1090,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 } } @@ -1065,16 +1123,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 } @@ -1086,18 +1144,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" } @@ -1107,18 +1165,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 @@ -1132,20 +1190,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 @@ -1157,12 +1215,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 } @@ -1170,12 +1228,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 @@ -1185,14 +1243,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 { @@ -1200,7 +1258,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 } @@ -1210,7 +1268,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 } @@ -1218,10 +1276,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 = @() @@ -1235,65 +1293,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] @@ -1313,24 +1371,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 @@ -1345,7 +1403,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 { @@ -1353,7 +1411,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 } } @@ -1363,24 +1421,24 @@ if ($PsBoundParameters.ContainsKey("startup")) { } } - Write-PowerManagementLogMessage -Type INFO -Message "##################################################################################" + Write-LogMessage -Type INFO -Message "##################################################################################" 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 INFO -Message "vSphere vSphere High Availability has been enabled by the script. Please disable it according to your environment's design." } - 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 "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 "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 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 "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..e0f3646 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 ) @@ -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 @@ -127,7 +187,7 @@ Try { } } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } # Gather details from SDDC Manager @@ -320,7 +380,7 @@ Try { Exit } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } # Run the Shutdown procedures @@ -749,7 +809,7 @@ Try { $index += 1 } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } # Startup procedures @@ -1093,5 +1153,5 @@ Try { } } } Catch { - Debug-CatchWriterForPowerManagement -object $_ + Write-DebugMessage -object $_ } diff --git a/VMware.CloudFoundation.PowerManagement.psm1 b/VMware.CloudFoundation.PowerManagement.psm1 index 0a03b01..485f2a5 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,16 +2209,16 @@ 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 @@ -2254,30 +2254,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 @@ -2317,9 +2317,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 } @@ -2327,52 +2327,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 @@ -2428,9 +2429,8 @@ Function Write-PowerManagementLogMessage { Write-Error -Message $Message } } -Export-ModuleMember -Function Write-PowerManagementLogMessage -Function Debug-CatchWriterForPowerManagement { +Function Write-DebugMessage { Param ( [Parameter (Mandatory = $true)] [PSObject]$object ) @@ -2438,9 +2438,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 }