PowerRestCLI.psm1

Write-Verbose 'Importing from [C:\projects\powerrestcli\PowerRestCLI\private]'
# .\PowerRestCLI\private\Invoke-ConnectionVariableSet.ps1
function Invoke-ConnectionVariableSet
{
    <#
    .DESCRIPTION
        Simple function to store variables..
    .EXAMPLE
        Invoke-ConnectionVariables
    .NOTES
        No notes.
    #>
    
    # Edit the vCenter IP to your server's IP or DNS name.
    [string]$script:vCenter = "192.168.2.220"
    [object]$script:headers = @()
    [object]$script:session = @()
    return $true

}
# .\PowerRestCLI\private\Invoke-SSLIgnore.ps1
function Invoke-SSLIgnore
{
    <#
    .DESCRIPTION
        Ignore SSL validation.
    .EXAMPLE
        Invoke-SSLIgnore
    .NOTES
        No notes.
    #>

    begin
    {
        # No code.
    }
    process 
    {    
        if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
        {
            $certCallback = @"
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public class ServerCertificateValidationCallback {
    public static void Ignore(){
        if(ServicePointManager.ServerCertificateValidationCallback ==null){
            ServicePointManager.ServerCertificateValidationCallback +=
            delegate(
                Object obj,
                X509Certificate certificate,
                X509Chain chain,
                SslPolicyErrors errors
            ){
                return true;
            };
        }
    }
}
"@

            Add-Type $certCallback
        }      
        [ServerCertificateValidationCallback]::Ignore();
        return $true
    }
}
# .\PowerRestCLI\private\New-rVIHeader.ps1
function New-rVIHeader
{
    <#
    .DESCRIPTION
        Gather Credentials to to add to Connection headers.
    .EXAMPLE
        New-rViHeaders
    .EXAMPLE
        New-rViHeader -Credential $Credentials
    .EXAMPLE
        $script:header = New-rViHeaders
    .PARAMETER Credential
        A valid Credential set is required.
    .NOTES
        No notes at this time.
    #>

    [CmdletBinding(
        SupportsShouldProcess = $true,
        ConfirmImpact = "Low"
    )]
    [OutputType([Hashtable])]
    [OutputType([boolean])]
    param(
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]$Credential
    )    
    begin 
    {
        # No pre-task
    }
    process
    {
        if ($pscmdlet.ShouldProcess("Creating Headers."))
        { 
            $auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Credential.UserName + ':' + $Credential.GetNetworkCredential().Password))
            $script:headers = @{
                'Authorization' = "Basic $auth"
            }
            return $script:headers
        } 
        else
        {
            # -WhatIf was used.
            return $false
        }
    }    
}
# .\PowerRestCLI\private\New-rVIsession.ps1
function New-rVIsession
{
    <#
    .DESCRIPTION
        Perform Rest API call to retrieve new Session token.
    .PARAMETER vCenter
        A valid vCenter IP/Name is required
    .PARAMETER Headers
        Valid Headers need to passed in.
    .EXAMPLE
        $script:session = New-rVisession -headers $headers -vCenter $vCenter
    .NOTES
        No Notes.
    #>

    [CmdletBinding(
        SupportsShouldProcess = $true,
        ConfirmImpact = "Low"
    )]
    [OutputType([Hashtable])]
    [OutputType([boolean])]
    param(
        [Parameter(Mandatory = $false)]
        [system.object]$headers,
        [Parameter(Mandatory = $true)]
        [string]$vCenter
    )    
    begin 
    {
        # No Pre-Task.
    }
    process
    {
        if ($pscmdlet.ShouldProcess("Creating Session."))
        { 
            # Perform Rest call to create session.
            $ReturnData = Invoke-RestMethod -Uri https://$vCenter/rest/com/vmware/cis/session -Method Post -Headers $headers -UseBasicParsing
            $token = ($ReturnData).value
            if ($null -ne $token)
            {
                $script:session = @{'vmware-api-session-id' = $token}
                return $script:session
            }
            else
            {
                # No token returned.
                Write-Error "No token returned."
                return $false
            }
        }
        else
        {
            # -WhatIf was used.
            return $false
        }
    }   
}
Write-Verbose 'Importing from [C:\projects\powerrestcli\PowerRestCLI\public]'
# .\PowerRestCLI\public\Connect-rVIServer.ps1
function Connect-rVIServer
{
    <#
    .DESCRIPTION
        Retrieve a Session token from vSphere API server.
    .PARAMETER vCenter
        A valid vCenter IP/Name is required as a variable called $vCenter
    .PARAMETER User
        A valid vCenter User is required
    .PARAMETER Password
        A valid vCenter Password is required
    .PARAMETER Credential
        A valid Credential set is required
    .EXAMPLE
        Connect-rVIServer -vCenter $vCenter -Credential $Credentials
    .EXAMPLE
        Connect-rVIServer -vCenter $vCenter -user "administrator@corp.local" -password (ConvertTo-SecureString "VMware1!" -AsPlainText -force)
    .EXAMPLE
        Connect-rVIServer -vCenter $vCenter -user "administrator@corp.local" -password (read-host -AsSecureString)
    .EXAMPLE
        Connect-rVIServer -vCenter $vCenter
    .NOTES
        Returns a Session to the powershell console, If the variable is global it does not need
        to be catpured in a variable.
    #>

    [CmdletBinding()]
    [OutputType([boolean])]
    param(
        [Parameter(Mandatory = $true, ParameterSetName = 'Credential')]
        [Parameter(Mandatory = $true, ParameterSetName = 'PlainText')]
        [Parameter(Mandatory = $true, ParameterSetName = 'NoCreds')]
        [string]$vCenter,
        [Parameter(Mandatory = $true,
            ParameterSetName = 'Credential')]
        [System.Management.Automation.PSCredential]$Credential,
        [Parameter(Mandatory = $true,
            ParameterSetName = 'PlainText')]
        [string]$User,
        [Parameter(Mandatory = $true,
            ParameterSetName = 'PlainText')]
        [System.Security.SecureString]$Password
    )
    try
    {
        # Ensure the PowerShell environment is set up to ignore self signed certs.
        if (Invoke-SSLIgnore)
        {
            # SSL was ignored
        }
        else 
        {
            Write-Error "Unable to Ignore SSL."
            return $false
        }
        # Determine the credential type to create appropriate header.
        if ($PSCmdlet.ParameterSetName -eq 'NoCreds')
        {
            # No Credential information was presented. Prompt user for credentials.
            $Credential = Get-Credential
        }
        elseif ($PSCmdlet.ParameterSetName -eq 'PlainText')
        {
            # User passed in Username/Password combo.
            $Credential = New-Object System.Management.Automation.PSCredential -ArgumentList ($user, $Password)
        }
        else
        {
            # User provided Credential Variable, No action needed.
        }
        # Insert the Credentials into the Header
        $script:headers = New-rViHeader -Credential $Credential
        # Validate that the headers are not empty.
        if ($script:headers -eq $false)
        {
            Write-Error "Unable to create Header."
            return $false
        }
        # Perform a Rest call and retrieve a token.
        $script:session = New-rVisession -headers $script:headers -vCenter $vCenter
        if ($script:session -eq $false)
        {
            Write-Error "Unable to establish session."
            return $false
        }
        $User = $Credential.UserName
        $vCenterReturn = New-Object -TypeName PSObject
        $vCenterReturn | Add-Member -MemberType NoteProperty -Name Name -Value $vCenter
        $vCenterReturn | Add-Member -MemberType NoteProperty -Name Port -Value "443"
        $vCenterReturn | Add-Member -MemberType NoteProperty -Name User -Value $User
        # Return vCenter connection information.
        $vCenterReturn 
    }
    Catch
    {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName        
        Write-Error "Error: $ErrorMessage $FailedItem"
        BREAK            
    }    
}
# .\PowerRestCLI\public\Get-rVM.ps1
function Get-rVM
{
    <#
    .SYNOPSIS
        Perform Rest API call to retrieve VM information from vCenter.
    .DESCRIPTION
        Perform Rest API call to retrieve VM information from vCenter.
    .PARAMETER vCenter
        A valid vCenter IP/Name is required at this time.
    .PARAMETER Headers
        Valid Headers need to be passed in.
    .PARAMETER Session
        Valid Session needs to be passed in.
    .EXAMPLE
        $vms = Get-rVM
    .NOTES
        No notes.
    #>

    begin
    {
        # Perform RestAPI call to vCenter to retrieve VM data.
        $ReturnData = Invoke-RestMethod -Uri https://$script:vCenter/rest/vcenter/vm -Method Get -Headers $script:session -UseBasicParsing
    } 
    Process
    {
        # Validate there was information Returned.
        if ($null -ne $ReturnData.value)
        {
            # Grab the data, and Format it in a table.
            $vms = ($ReturnData).value
            $mydata = $vms | Format-Table name, Power_State, cpu_count, memory_size_MiB -AutoSize
            return $mydata
        }
        else
        {
            # Return an error if no data was returned from REST.
            Write-Error "Did not recieve a valid response."
            return $false
        }
    }
}
Write-Verbose 'Importing from [C:\projects\powerrestcli\PowerRestCLI\classes]'