EsxiInventoryTools.psm1

$CachedTokenPath = "$env:localappdata\esxiinventorytools_cached_token.dat"
function Publish-EsxiInventory {
<#
.SYNOPSIS
Command to Publish ESXiInventory to a URI location, such as Eagles Nest.
.DESCRIPTION
Publish-ESXiInventory does the following in the following order:
-Gets Token from locally encrypted dat file. This encrypted dat file is set by Initialize-ESXiInventoryTools.
-Accesses the secret from Vault using the Token
-Connects to VI server and gathers Host inventory
-Submits the Host inventory to the PublishURI location
.PARAMETER VIServer
The VIServer to connect to gather inventory.
.PARAMETER PublishURI
The URI to publish to.
.PARAMETER Vault_Full_Address
The full hashicorp vault address from where to obtain the vault_key from
.PARAMETER Vault_Key
The vault key used to obtain the value
.EXAMPLE
Publish-ESXiInventory
This example publishes the ESXi Inventory.
#>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [string]$VIServer,

        [Parameter(Mandatory=$true)]
        [string]$PublishURI,

        [Parameter(Mandatory=$true)]
        [string]$Vault_Full_Address,

        [Parameter(Mandatory=$true)]
        [string]$Vault_Key
    )

    $InformationPreference='Continue'

    #Begin
    Try {
        $ErrorActionPreference = 'Stop'

        $GetValueParams = @{
            Vault_Full_Address = $Vault_Full_Address
            Vault_SavedTokenPath = $CachedTokenPath
            Vault_Key = $Vault_Key
        }
        $PUBLISH_API_KEY = Get-VaultValue @GetValueParams
        Write-Information "Retrieved Api Key from Vault"

        #Connect to VIServer
        $ConnectParams = @{
            Server = $VIServer
            Protocol = 'https'
        }
        Connect-VIServer @ConnectParams | Out-Null
        Write-Information "Connected to VIServer $VIServer"

        #Get Hosts from VIServer - Specify Get-VMHost from Vmware module
        [ValidateNotNullOrEmpty()]$ESXiHosts = Vmware.VimAutomation.Core\Get-VMHost
        $ESXiHostCount = ($ESXiHosts | Measure-Object).Count
        Write-Information "Retrieved $ESXiHostCount Hosts from VIServer"

        #Custom Inventory Object
        class ESXiItem {
            #Instance Properties
            [string]$Serial_Number
            [string]$Asset_Name
            [string]$Manufacturer
            [string]$Model
            [string]$Operating_System
            [string]$OS_Version
            [string]$IP_Address
            [string]$MAC_Address
            [string]$UpdateTime

            #Constructor - required properties
            ESXiItem ($VMHostImpl) {
                $this.Asset_Name=$VMHostImpl.Name
                $this.Serial_Number=(Vmware.VimAutomation.Core\Get-VMHostHardware -VMHost $VMHostImpl.Name).SerialNumber
                $this.Manufacturer=$VMHostImpl.Manufacturer
                $this.Model=$VMHostImpl.Model
                $this.Operating_System=(Vmware.VimAutomation.Core\Get-View -ViewType HostSystem -Filter @{"Name" = $VMHostImpl.Name}).Config.Product.Name
                $this.OS_Version=(Vmware.VimAutomation.Core\Get-View -ViewType HostSystem -Filter @{"Name" = $VMHostImpl.Name}).Config.Product.Version
                $this.IP_Address=(Vmware.VimAutomation.Core\Get-VMHostNetworkAdapter -VMHost $VMHostImpl.Name | Where-Object {$_.Name -eq 'vmk0'}).IP
                $this.MAC_Address=(Vmware.VimAutomation.Core\Get-VMHostNetworkAdapter -VMHost $VMHostImpl.Name | Where-Object {$_.Name -eq 'vmk0'}).Mac
                $this.UpdateTime=(Get-Date).Tostring()
            }
        }
    }
    Catch {
        $ErrorActionPreference = 'Continue' #so error continues down pipeline for logging
        $PSCmdlet.WriteError($_)
        Break
    }

    #Process
    $Inventory=@()
    ForEach ($ESXiHost in $ESXiHosts) {
        Try {
            $ErrorActionPreference='Stop'
            if (Test-Connection -ComputerName $ESXiHost.Name -Quiet -Count 1) {
                $InventoryItem = [ESXiItem]::New($ESXiHost)
                $Inventory += $InventoryItem
            }
        }
        Catch {
            $ErrorActionPreference = 'Continue' #so error continues down pipeline for logging
            $PSCmdlet.WriteError($_)
            Continue #continue to next esxi host
        }
    }

    #End
    Try {
        $ErrorActionPreference = 'Stop'

        #Inventory Count
        $InventoryCount = ($Inventory | Measure-Object).Count
        Write-Information "Inventory created for $InventoryCount of $ESXiHostCount hosts"

        #Submit the Inventory as JSON
        $JSONInventory = $Inventory | ConvertTo-Json
        $InvokeWebRequestParams = @{
            URI = $PublishURI
            Method = 'POST'
            Headers = @{"api_key" = "$PUBLISH_API_KEY";'Content-Type'='json'}
            Body = $JSONInventory
        }

        #Output Message
        $Response = Invoke-WebRequest @InvokeWebRequestParams
        if ($Response.StatusCode -eq '200') {
            Write-Information 'Content successfully submitted'
        }
    }
    Catch {
        $ErrorActionPreference = 'Continue' #so error continues down pipeline for logging
        $PSCmdlet.WriteError($_)
    }
    Finally {
        Try {
            $ErrorActionPreference = 'Stop'
            Disconnect-VIServer -Confirm:$false
            Write-Information "Disconnected from VIServer"
        }
        Catch {
            $ErrorActionPreference = 'Continue' #so error continues down pipeline for logging
            $PSCmdlet.WriteError($_)
        }
    }
}
function Register-EsxiInventoryTask {
<#
.SYNOPSIS
Command to register EsxiInventoryTools task
.DESCRIPTION
sets the cached token, event log, and scheduled task
.PARAMETER LdapCredential
The ldap credential used to obtain a token
.PARAMETER Vault_Rolename
The approle which has access to the secret in vault
.PARAMETER Logname
The event log to use for event logging
.PARAMETER Source
The event log source to use for event logging
.PARAMETER DailyRunTime
The time to schedule the daily task for. (e.g. '9pm', '9:30am')
.PARAMETER VIServer
The vcenter server to connect to
.PARAMETER PublishURI
The server to publish the inventory to
.PARAMETER Vault_Full_Address
The full hashicorp vault address from where to obtain the vault_key from
.PARAMETER Vault_Key
The vault key used to obtain the value
#>

    [CmdletBinding()]
    Param(
        #Token params
        [Parameter(Mandatory=$true)]
        [System.Management.Automation.PSCredential]$LdapCredential,

        [Parameter(Mandatory=$true)]
        [string]$Vault_Rolename,

        #ScheduledTask and EventLog params
        [Parameter(Mandatory=$true)]
        [string]$LogName,

        [Parameter(Mandatory=$true)]
        [string]$Source,

        #ScheduledTask params
        [Parameter(Mandatory=$true)]
        [string]$DailyRunTime,

        [Parameter(Mandatory=$true)]
        [string]$VIServer,

        [Parameter(Mandatory=$true)]
        [string]$PublishURI,

        [Parameter(Mandatory=$true)]
        [ValidateScript({$_ -match 'https'})]
        [string]$Vault_Full_Address,

        [Parameter(Mandatory=$true)]
        [string]$Vault_Key
    )

    $ErrorActionPreference = 'Stop'
    $Verbose = $VerbosePreference -ne 'SilentlyContinue'

    #Token
    $Vault_Full_Address -match 'https://[\w\.]*' | Out-Null
    $Vault_Address = $Matches[0]
    $PublishTokenParams = @{
        LdapCredential = $LdapCredential
        Vault_Address = $Vault_Address
        Vault_RoleName = $Vault_RoleName
        Verbose = $Verbose
    }
    Install-EsxiInventoryToken @PublishTokenParams

    #Install Module for writing to eventlog, then install event log
    Try {
        Install-Module -Name 'EventLogTools' -RequiredVersion '2.3' -Repository 'PSGallery' -Force
        New-EventLog -LogName $LogName -Source $Source -ErrorAction 'Stop' -ErrorVariable 'NewEventLog' -Verbose:$Verbose
    }
    Catch {
        if ($NewEventLog -notmatch 'already registered') {
            $PSCmdlet.WriteError($_)
        }
    }

    #Commands for Scheduled Job
    $Name = 'Publish_EsxiInventory'
    $RunCommand="Publish-EsxiInventory -VIServer $VIServer -PublishURI $PublishURI -Vault_Full_Address $Vault_Full_Address -Vault_Key $Vault_Key"
    $LogCommand=" *>&1 | Write-StreamToEventLog -AutoID 'Hash' -LogName $Logname -Source $Source"
    $CompleteCommand = $RunCommand + $LogCommand
    $ScriptBlock = [scriptblock]::Create("$CompleteCommand")

    #Register Scheduled Job
    if (Get-ScheduledJob | Where-Object {$_.Name -eq $Name}) {Unregister-ScheduledJob -Name $Name}
    $JobParams = @{
        Name = $Name
        ScriptBlock = $ScriptBlock
        Trigger = New-JobTrigger -Daily -At $DailyRunTime
        ScheduledJobOption = New-ScheduledJobOption -RunElevated -RequireNetwork -MultipleInstancePolicy 'StopExisting'
        Credential = $LdapCredential
        Verbose = $Verbose
    }
    Register-ScheduledJob @JobParams | Out-Null
}
function Install-EsxiInventoryToken {
<#
.SYNOPSIS
Command to setup publish token
.DESCRIPTION
Stores a local token used to access the Publish Api key stored in vault.
The token is a representation of the secret ID for the approle used to access the Publish Api key.
This command needs to be run before Publish-EsxiInventory is run on a new computer and/or when the token expires.
.PARAMETER LdapCredential
The ldap username and password credentials used to access $Vault_Address
.PARAMETER Vault_Address
The address to the hashicorp vault. Format is: 'https://myvaultaddress'.
.PARAMETER Vault_Rolename
The name of the approle used to access secrets stored in hashicorp vault.
.EXAMPLE
Install-EsxiInventoryTools -LdapCredential (Get-Credential)
#>

    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [System.Management.Automation.PSCredential]$LdapCredential,

        [Parameter(Mandatory=$true)]
        [ValidateScript({$_ -match 'https'})]
        [ValidateScript({$_ -notmatch '/$' -and $_ -notmatch '/v1$'})]
        [string]$Vault_Address,

        [Parameter(Mandatory=$true)]
        [string]$Vault_Rolename
    )


    $Verbose = $VerbosePreference -ne 'SilentlyContinue'
    $ErrorActionPreference = 'Stop'

    #Save Token
    $Save_VaultToken_Params = @{
        LdapCredential = $LdapCredential
        Vault_Address = $Vault_Address
        Vault_Rolename = $Vault_Rolename
        OutputPath = $CachedTokenPath
        Verbose = $Verbose
    }
    Save-VaultToken @Save_VaultToken_Params
}