PowerRestCLI.psm1

Write-Verbose 'Importing from [C:\projects\powerrestcli\PowerRestCLI\private]'
# .\PowerRestCLI\private\Get-rVIsession.ps1
function Get-rVisession
{
    param(
        [Parameter(Mandatory = $false)]
        [system.object]$head,
        [Parameter(Mandatory = $false)]
        [string]$vCenter
    )
    $r = Invoke-WebRequest -Uri https://$vCenter/rest/com/vmware/cis/session -Method Post -Headers $head -UseBasicParsing
    $token = (ConvertFrom-Json $r.Content).value
    $script:session = @{'vmware-api-session-id' = $token}
    $script:session
}
# .\PowerRestCLI\private\Invoke-SSLIgnore.ps1
function Invoke-SSLIgnore
{
    <#
    .DESCRIPTION
        Ignore SSL validation.
    .EXAMPLE
        Invoke-SSLIgnore
    .NOTES
        No notes.
    #>

    try 
    {    
        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();
    }
    catch
    {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName        
        Write-Error "Error: $ErrorMessage $FailedItem"
        BREAK           
    }

}
# .\PowerRestCLI\private\New-rVIHeader.ps1
function New-rVIHeader
{
    <#
    .DESCRIPTION
        Gather Credentials to to add to Connection headers.
    .EXAMPLE
        New-rViHeaders
    .EXAMPLE
        New-rViHeaders -Credential $Credentials
    .EXAMPLE
        $script:headers = New-rViHeaders
    .NOTES
        No notes at this time.
    #>

    [CmdletBinding(
        SupportsShouldProcess = $true,
        ConfirmImpact = "Low"
    )]
    [OutputType([Hashtable])]
    param(
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]$Credential
    )    
    try 
    {
        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
        }
    }
    Catch
    {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName        
        Write-Error "Error: $ErrorMessage $FailedItem"
        BREAK            
    }    
}
# .\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])]
    param(
        [Parameter(Mandatory = $false)]
        [system.object]$headers,
        [Parameter(Mandatory = $true)]
        [string]$vCenter
    )    
    try 
    {
        if ($pscmdlet.ShouldProcess("Creating Session."))
        { 
            # Perform Rest call to create session.
            $ReturnData = Invoke-WebRequest -Uri https://$vCenter/rest/com/vmware/cis/session -Method Post -Headers $headers -UseBasicParsing
            $token = (ConvertFrom-Json $ReturnData.Content).value
            $script:session = @{'vmware-api-session-id' = $token}
            return $script:session
        }
    }
    Catch
    {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName        
        Write-Error "Error: $ErrorMessage $FailedItem"
        BREAK            
    }     
}
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
    .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
        New-rVisession -vCenter $vCenter -Credential $Credentials
    .EXAMPLE
        New-rVisession -vCenter $vCenter -user "administrator@corp.local" -password "VMware1!"
    .EXAMPLE
        $session = New-rVisession -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()]
    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.
        Invoke-SSLIgnore
        # Determine the credential type to create appropriate header.
        if ($PSCmdlet.ParameterSetName -eq 'Credential') 
        {
            $script:headers = New-rViHeaders -Credentials $Credential
        }
        elseif ($PSCmdlet.ParameterSetName -eq 'PlainText') 
        {
            $Credential = New-Object System.Management.Automation.PSCredential -ArgumentList ($user, $Password)
            $script:headers = New-rViHeaders -Credential $Credential
        }
        else 
        {
            # Prompt user for vCenter Username and password.
            $Credential = Get-Credential
            $script:headers = New-rViHeaders
        }     
        # Perform a Rest call and retrieve a token.
        $script:session = New-rVisession -headers $script:headers -vCenter $vCenter
        $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 
        $vCenterReturn 
    }
    Catch
    {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName        
        Write-Error "Error: $ErrorMessage $FailedItem"
        BREAK            
    }    
}
# .\PowerRestCLI\public\ConnectionVariables.ps1
# 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 = @()
# .\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.
    #>

    try 
    {
        # Perform RestAPI call to vCenter to retrieve VM data.
        $ReturnData = Invoke-WebRequest -Uri https://$script:vCenter/rest/vcenter/vm -Method Get -Headers $script:session -UseBasicParsing
        $vms = (ConvertFrom-Json $ReturnData.Content).value
        $mydata = $vms | Format-Table name, Power_State, cpu_count, memory_size_MiB -AutoSize
        return $mydata    
    }
    Catch
    {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName        
        Write-Error "Error: $ErrorMessage $FailedItem"
        BREAK            
    }
}
Write-Verbose 'Importing from [C:\projects\powerrestcli\PowerRestCLI\classes]'