VMware Cloud Community
vkaranam
Enthusiast
Enthusiast
Jump to solution

How to Report the current time on ESX host in to a csv along with the following

Hello guys

I have the following script where i am getting the required details except the current time on the ESX host. Can anyone please guide me.

foreach ($esx in $vmhosts) {
$hostVC=$vcenter
$hostCluster=$esx.Parent.Name
$hostHost=$esx.Name
$ntp = $esx | Get-VMHostNtpServer
$hostNTP = "$ntp"

                   

}

I want to integrate the following for loop in the above for loop and ge the output in a single table.

                foreach($esxcli in get-vmhost|get-esxcli){""|select @{n='Time';e={$esxcli.system.time.get()}},@{n='hostname';e={$esxcli.system.hostname.get().hostname}} }

Add-Content -Path $hostInvFile "$hostVC,$hostCluster,$hostHost,$hostNTP,$hostTime" - $ hostTime is where i want to get my host current time.

I am getting vcenter name, esx name, cluster name, host ntp server address but i need the host current time as well.

Thanks in advance.

Thanks

vKar

0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

Try changing the line where the script fetches the VMHost to this

$vmhosts = Get-VMHost -State Connected | Sort Name

That way the script will only at ESXi nodes that are "connected".

Fetching the time for the faulty ones doesn't make much sense in any case


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

View solution in original post

0 Kudos
15 Replies
LucD
Leadership
Leadership
Jump to solution

Try something like this

Get-VMHost | %{

    New-Object PSObject -Property @{

        Name = $_.Name

        Cluster = $_.Parent.Name

        vCenter = $_.Uid.Split('@')[1].Split(':')[0]

        NTP = (Get-VMHostNtpServer -VMHost $_) -join '|'

        Time = (Get-EsxCli -VMHost $_).System.Time.get()

    }

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

vkaranam
Enthusiast
Enthusiast
Jump to solution

Hello LucD,

Thanks for the reply. Can you the code that was given by you in the for loop. I have to run this script on 20 vcenters without interruption. I have created a csv file with the vcenter name and user credentials and for each host in that vcenter i have get the report of vcenter name, host, cluster, ntp time and current host time.

can i use the Name, Cluster, vCenter, NTP and time in the Add content in my first message. Please let me know.

Thanks

vKar

0 Kudos
vkaranam
Enthusiast
Enthusiast
Jump to solution

Lucd,

For clear understanding here is the complete script.

# VAR DECLARATIONS

$date = ((Get-Date).ToString("MMddyyyy"))

#$vCenterFile = "vCenters7.csv"

$vCenterFile = "vCenters-Encrypted.csv"

$hostInvFile = "host_inventory-$date.csv"

$vcInvFile = "host_inv_vc_errors-$date.csv"

Clear-Host

$path = Split-Path ($MyInvocation.MyCommand.Path)

Set-Location $path

# Load PowerCLI snapin

if (-not (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {

  Add-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue

  if ($LASTEXITCODE -eq 0) {

  sleep 5

  Add-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue

  if (!$?) {

  Write-Error "Unable to add VMware.VimAutomation.Core snapin"

  Start-Process -FilePath 'http://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli'

  exit

  }

  }

}

# Verify PowerCLI version

if ((Get-PowerCLIVersion).Major -lt 5) {

  $Response = Read-Host "PowerCLI 5 not found.  Script may not run properly.  Do you want to continue? [n = No, default = Yes]"

  if ($Response -eq "n") {

  Start-Process -FilePath 'http://communities.vmware.com/community/vmtn/server/vsphere/automationtools/powercli'

  exit

  }

  Remove-Variable Response -Confirm:$false

}

# Verify PowerShell version

if ($Host.Version.Major -lt 2) {

  Write-Error "PowerShell version 2 or greater is required"

  exit

}

Set-PowerCLIConfiguration -ProxyPolicy NoProxy -DefaultVIServerMode Single -InvalidCertificateAction Ignore -Confirm:$false | Out-Null

trap { continue }

if (!(Test-Path $path\$vCenterFile)) {

  Write-error "Missing vCenter file"

  exit

}

$allVC = Import-Csv $path\$vCenterFile -ErrorAction SilentlyContinue | Sort vCenter

if (-not (Test-Path $path\$date)) {

  New-Item -ItemType Directory $path\$date -ErrorAction SilentlyContinue | Out-Null

}

$hostInvFile = "$path\$date\" + $hostInvFile

$vcInvFile = "$path\$date\" + $vcInvFile

if (Test-Path $hostInvFile) {

  rm $hostInvFile -Confirm:$false | Out-Null

}

New-Item $hostInvFile -ItemType File | Out-Null

if (Test-Path $vcInvFile) {

  rm $vcInvFile -Confirm:$false | Out-Null

}

New-Item $vcInvFile -ItemType File | Out-Null

Set-Content -Encoding UTF8 -Path $hostInvFile "vCenter,Cluster,Host,NTP,Hosttime"

Set-Content -Encoding UTF8 -Path $vcInvFile "vCenter,Connection"

$vcarray = @()

$vmhosts = @()

$esxpass = Read-Host "Enter ESX root password" -AsSecureString

$rootCred = New-Object System.Management.Automation.PSCredential("root",$esxpass)

foreach ($vc in $allVC) {

  $vCenter = $vc.vCenter

  if ($vc.Comment -notmatch "host") {

  $vcUser = $vc.User

  $vcPass = ConvertTo-SecureString -String $vc.Pass -Key (1..16)

  $vcCred = New-Object System.Management.Automation.PSCredential($vcUser,$vcPass)

  Write-Host $vCenter":"

  $vcConnect = Connect-VIServer $vCenter -Credential $vcCred -WarningAction SilentlyContinue -ErrorAction SilentlyContinue

  } else {

  Write-Host $vCenter":"

  $vcConnect = Connect-VIServer $vCenter -cred $rootCred -WarningAction SilentlyContinue -ErrorAction SilentlyContinue

  }

  if (!$vcConnect) {

  $vcConnection = "Failed"

  Write-Host " >Failed" -ForegroundColor Red

  Add-Content -Path $vcInvFile "$vcenter,$vcConnection"

  }

  else {

  Write-Host " >Successful"

  $vcConnection = "Successful"

  $vmhosts = Get-VMHost | Sort Name

  foreach ($esx in $vmhosts) {

  $hostVC=$vcenter

  $hostCluster=$esx.Parent.Name

  $hostHost=$esx.Name

  $dns = ($esx | Get-VMHostNetwork).DnsAddress

  $hostDNS = "$dns"

  $ntp = $esx | Get-VMHostNtpServer

The below is the one i am unable to fix. The host current time. Please help.

 

           #$time = ($esx | get-esxcli)|select @{n='Time';e={$esxcli.system.time.get()}}

            #$time = $esx | Get-VMhost $_.ConfigManager.DateTimeSystem

  $hostTime = "$time"

  }

  Add-Content -Path $hostInvFile "$hostVC,$hostCluster,$hostHost,$hostNTP,$hostTime"

  }

  Add-Content -Path $vcInvFile "$vcenter,$vcConnection"

  Disconnect-VIServer -Server $vcenter -Confirm:$false -ErrorAction SilentlyContinue

  }

Invoke-Item $path\$date

Write-Host "Execution completes ... Exiting"

Thanks

vKar

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Did you already try that line as

$time = (Get-EsxCli -VMHost $esx).system.time.get()


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
vkaranam
Enthusiast
Enthusiast
Jump to solution

Hello Lucd,

tried that and i am getting this error.

Get-EsxCli : 2/25/2016 5:18:28 PM    Get-EsxCli        Message: vim.fault.NoHost;

InnerText: Invalid fault   

At DHost NTP.ps1:131 char:22

+             $time = (Get-EsxCli -VMHost $esx).system.time.get()

+                      ~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [Get-EsxCli], ViError

    + FullyQualifiedErrorId : Client20_DynamicTypeManagerServiceImpl_GetMoInstances_ViError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetEsxCli

$time = (Get-EsxCli -VMHost $esx).system.time.get()

  $hostTime = "$time"

  }

  Add-Content -Path $hostInvFile "$hostVC,$hostCluster,$hostHost,$hostNTP,$hostTime"

  }

  Add-Content -Path $vcInvFile "$vcenter,$vcConnection"

  Disconnect-VIServer -Server $vcenter -Confirm:$false -ErrorAction SilentlyContinue

  }

What might be the problem.

i am calling the $time variable in to the another varialble $ host time.

Thanks

vKar

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Did you place that line inside the foreach loop that starts with

foreach ($esx in $vmhosts) {

It seems the value of $esx is $null in this case.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
vkaranam
Enthusiast
Enthusiast
Jump to solution

Hello LucD

Here is the for loop.

  foreach ($esx in $vmhosts) {

  $hostVC=$vcenter

  $hostCluster=$esx.Parent.Name

  $hostHost=$esx.Name

  #$dns = ($esx | Get-VMHostNetwork).DnsAddress

  #$hostDNS = "$dns"

  $ntp = $esx | Get-VMHostNtpServer

  $hostNTP = "$ntp"

  $time = (Get-EsxCli -VMHost $esx).system.time.get()

             $hostTime = "$time"

  }

  Add-Content -Path $hostInvFile "$hostVC,$hostCluster,$hostHost,$hostNTP,$hostTime"

  }

  Add-Content -Path $vcInvFile "$vcenter,$vcConnection"

Let me know any questions

Thanks

vKar

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Looks like you placed the Add-Content outside the ForEach loop.

Seems you also forgot the $hostDNS in the output.

Try like this

if (!$vcConnect) {

  $vcConnection = "Failed"

  Write-Host " >Failed" -ForegroundColor Red

  Add-Content -Path $vcInvFile "$vcenter,$vcConnection"

}

else {

  Write-Host " >Successful"

  $vcConnection = "Successful"

  $vmhosts = Get-VMHost | Sort Name

  foreach ($esx in $vmhosts) {

    $hostVC=$vcenter

    $hostCluster=$esx.Parent.Name

    $hostHost=$esx.Name

    $hostDNS = ($esx | Get-VMHostNetwork).DnsAddress

    $hostNTP = $esx | Get-VMHostNtpServer

    $hostTime = (Get-EsxCli -VMHost $esx).system.time.get()

    Add-Content -Path $hostInvFile "$hostVC,$hostCluster,$hostHost,$hostDNS,$hostNTP,$hostTime"

  }

}

 


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

vkaranam
Enthusiast
Enthusiast
Jump to solution

Hello LucD,

The above script helped and i am getting the required output. but still getting this error.

Get-EsxCli : 2/29/2016 10:43:05 AM    Get-EsxCli        Message: vim.fault.NoHost;

InnerText: Invalid fault   

At D:\Scripts\Host NTP Script\Host NTP.ps1:145 char:26

+             $hostTime = (Get-EsxCli -VMHost $esx).system.time.get()

+                          ~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [Get-EsxCli], ViError

    + FullyQualifiedErrorId : Client20_DynamicTypeManagerServiceImpl_GetMoInstances_ViError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetEsxCli

Execution completes ... Exiting

Now i want to add the date and time the script was ran and compare that date and time to the ESX host time that was reported in the script so that i will know any time differences on the hosts. is that possible. I rellay appreciate all the help.

Thanks

vkar.

0 Kudos
vkaranam
Enthusiast
Enthusiast
Jump to solution

I have added the date so that i can compare the sript ran time and the esx time side by side.

Here is the for loop

foreach ($vc in $allVC) {

  $vCenter = $vc.vCenter

  if ($vc.Comment -notmatch "host") {

  $vcUser = $vc.User

  $vcPass = ConvertTo-SecureString -String $vc.Pass -Key (1..16)

  $vcCred = New-Object System.Management.Automation.PSCredential($vcUser,$vcPass)

  Write-Host $vCenter":"

  $vcConnect = Connect-VIServer $vCenter -Credential $vcCred -WarningAction SilentlyContinue -ErrorAction SilentlyContinue

  } else {

  Write-Host $vCenter":"

  $vcConnect = Connect-VIServer $vCenter -cred $rootCred -WarningAction SilentlyContinue -ErrorAction SilentlyContinue

  }

  if (!$vcConnect) {

  $vcConnection = "Failed"

  Write-Host " >Failed" -ForegroundColor Red

  Add-Content -Path $vcInvFile "$vcenter,$vcConnection"

  }

  else {

  Write-Host " >Successful"

  $vcConnection = "Successful"

  $vmhosts = Get-VMHost | Sort Name

  foreach ($esx in $vmhosts) {

  $hostVC=$vcenter

  $hostCluster=$esx.Parent.Name

  $hostHost=$esx.Name

  $hostNtp = $esx | Get-VMHostNtpServer

            $hostTime = (Get-EsxCli -VMHost $esx).system.time.get()

            $scriptTime = Get-Date -Format g #"dd-MMM-YY HH:mm" # This Will add the time when the Script was ran.

               Add-Content -Path $hostInvFile "$hostVC,$hostCluster,$hostHost,$hostNTP,$hostTime,$scriptTime"

  }

I am getting the output as expected.  the only problem was i am still getting this invalid fault error.

Get-EsxCli : 2/29/2016 11:35:10 AM    Get-EsxCli        Message: vim.fault.NoHost;

InnerText: Invalid fault   

At D:\Scripts\Host NTP Script\Host NTP.ps1:144 char:26

+             $hostTime = (Get-EsxCli -VMHost $esx).system.time.get()

+                          ~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [Get-EsxCli], ViError

    + FullyQualifiedErrorId : Client20_DynamicTypeManagerServiceImpl_GetMoInstances_ViError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetEsxCli


Can you please help me with this error.


Thanks

vKar

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Do you only get that error once in the script ?

If yes, that could mean there is a "ghost" or powered off ESXi node in the output of Get-VMHost.

You could check with checking the output of Get-VMHost.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

vkaranam
Enthusiast
Enthusiast
Jump to solution

Yes LucD,

Thanks for the reply.

I am getting that error one time. How can i add it in to the report - saying this host has been in disconnected state or the value (if the host UUID is misisng) is not present?

Please let me know

If it is not possible can i suppress the alert?

Thanks

vKar

0 Kudos
vkaranam
Enthusiast
Enthusiast
Jump to solution

Actually i have four ESXi host that are not responding in the vCenter. and i am getting the error  single time. But all the four hosts are under a single cluster.

Thanks

vKar

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Try changing the line where the script fetches the VMHost to this

$vmhosts = Get-VMHost -State Connected | Sort Name

That way the script will only at ESXi nodes that are "connected".

Fetching the time for the faulty ones doesn't make much sense in any case


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
vkaranam
Enthusiast
Enthusiast
Jump to solution

Yes that resolved the issue.

The script was running successfully. Thanks for the help LucD. i have another big task to go. Work on  the vmware health report.

Thanks a lot LucD

Thanks

vKar

0 Kudos