param(
    [string]$vCenterServer = "vcenter.vcapsie.corp",
    [string]$outputLocation = "C:\vcapsie"
)

# Function to log messages
function Write-Log {
    param(
        [string]$Message,
        [string]$Path
    )
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "${timestamp}: $Message" | Out-File -FilePath $Path -Append
}

# Credentials
$credentials = Get-Credential

# Log file preparation
$logFile = Join-Path -Path $outputLocation -ChildPath "ScriptLog.txt"

# Connect to vCenter
try {
    Connect-VIServer $vCenterServer -Credential $credentials -AllLinked
    Write-Log -Message "Connected to vCenter server: $vCenterServer" -Path $logFile
} catch {
    Write-Log -Message "Error connecting to vCenter: $_" -Path $logFile
    return
}

# Current date and filename preparation
$date = Get-Date -Format "yyyyMMddHHmm"
$filename = "$date-VMHostInfo.csv"
$path = Join-Path -Path $outputLocation -ChildPath $filename

# Ensure directory existence
if (-not (Test-Path -Path $outputLocation)) {
    New-Item -ItemType Directory -Path $outputLocation
    Write-Log -Message "Directory created at: $outputLocation" -Path $logFile
}

# Retrieve and process VM hosts information
$vmHosts = Get-VMHost
$cpuTotal = ($vmHosts | Measure-Object -Property NumCpu -Sum).Sum
$memTotal = ($vmHosts | Measure-Object -Property MemoryTotalGB -Sum).Sum

Write-Host "Total Number of CPUs across all VM hosts: $cpuTotal"
Write-Host "Total amount of Memory across all VM hosts: $($memTotal -as [int])"
Write-Log -Message "Total CPUs: $cpuTotal, Total Memory: $memTotal GB" -Path $logFile

$vmHostsInfo = $vmHosts | Select-Object Name, @{Name="Parent";Expression={$_.Parent}}, NumCpu, @{Name="MemoryGB";Expression={$_.MemoryTotalGB -as [int]}}
$vmHostsInfo | Export-Csv -Path $path -NoTypeInformation
Write-Host "VM hosts information exported to CSV file at: $path"
Write-Log -Message "VM hosts information exported to CSV file at: $path" -Path $logFile

# Disconnect from the vCenter Server
try {
    Disconnect-VIServer * -Confirm:$false
    Write-Log -Message "Disconnected from vCenter server" -Path $logFile
} catch {
    Write-Log -Message "Error disconnecting from vCenter: $_" -Path $logFile
}