Profile.ps1


<#PSScriptInfo
 
.VERSION 1.0
 
.GUID a9697818-4079-4c1a-af11-ff40f3ff647c
 
.AUTHOR
    Omer Barel
 
.COMPANYNAME
    JungoIT
 
.COPYRIGHT
    Omer Barel
 
.TAGS
    profile
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
    See Add-VMwareModules Function below
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
    This is my first release for a simple Powershell profile I wrote
 
#>


<#
 
.DESCRIPTION
 Sample PowerShell Profile
 For a getting started guide with profiles, read here - https://msdn.microsoft.com/en-us/powershell/scripting/core-powershell/ise/how-to-use-profiles-in-windows-powershell-ise
 This Profile will:
 * Load a bunch of functions to the memory so you can call them when needed. Most I gathered from others and added as-is
 * Load VMware PowerShell Modules in a function
   VMWare PowerCLI must be installed
   Latest version (6.3R1) can be found here - https://my.vmware.com/web/vmware/details?downloadGroup=PCLI630R1&productId=491
 * Load a script to the ISE window. I'm using a template script to keep my scripts organized and this helps so I can quickly copy-paste it to a new script window and start coding fast
 
#>
 

Param()


Function Log-ScriptEvent {

##########################################################################################################
<#
.SYNOPSIS
   Log to a file in a format that can be read by Trace32.exe / CMTrace.exe
 
.DESCRIPTION
   Write a line of data to a script log file in a format that can be parsed by Trace32.exe / CMTrace.exe
 
   The severity of the logged line can be set as:
 
        1 - Information
        2 - Warning
        3 - Error
 
   Warnings will be highlighted in yellow. Errors are highlighted in red.
 
   The tools to view the log:
 
   SMS Trace - http://www.microsoft.com/en-us/download/details.aspx?id=18153
   CM Trace - Installation directory on Configuration Manager 2012 Site Server - <Install Directory>\tools\
 
.EXAMPLE
   Log-ScriptEvent c:\output\update.log "Application of MS15-031 failed" Apply_Patch 3
 
   This will write a line to the update.log file in c:\output stating that "Application of MS15-031 failed".
   The source component will be Apply_Patch and the line will be highlighted in red as it is an error
   (severity - 3).
 
#>

##########################################################################################################

#Define and validate parameters
[CmdletBinding()]
Param(
      #Path to the log file
      [parameter(Mandatory=$True)]
      [String]$NewLog,

      #The information to log
      [parameter(Mandatory=$True)]
      [String]$Value,

      #The source of the error
      [parameter(Mandatory=$True)]
      [String]$Component,

      #The severity (1 - Information, 2- Warning, 3 - Error)
      [parameter(Mandatory=$True)]
      [ValidateRange(1,3)]
      [Single]$Severity
      )


#Obtain UTC offset
$DateTime = New-Object -ComObject WbemScripting.SWbemDateTime 
$DateTime.SetVarDate($(Get-Date))
$UtcValue = $DateTime.Value
$UtcOffset = $UtcValue.Substring(21, $UtcValue.Length - 21)


#Create the line to be logged
$LogLine =  "<![LOG[$Value]LOG]!>" +`
            "<time=`"$(Get-Date -Format HH:mm:ss.fff)$($UtcOffset)`" " +`
            "date=`"$(Get-Date -Format M-d-yyyy)`" " +`
            "component=`"$Component`" " +`
            "context=`"$([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)`" " +`
            "type=`"$Severity`" " +`
            "thread=`"$([Threading.Thread]::CurrentThread.ManagedThreadId)`" " +`
            "file=`"`">"

#Write the line to the passed log file
Add-Content -Path $NewLog -Value $LogLine

}

##########################################################################################################

Function Log-Start{
  <#
  .SYNOPSIS
    Creates log file
 
  .DESCRIPTION
    Creates log file with path and name that is passed. Checks if log file exists, and if it does deletes it and creates a new one.
    Once created, writes initial logging data
 
  .PARAMETER LogPath
    Mandatory. Path of where log is to be created. Example: C:\Windows\Temp
 
  .PARAMETER LogName
    Mandatory. Name of log file to be created. Example: Test_Script.log
       
  .PARAMETER ScriptVersion
    Mandatory. Version of the running script which will be written in the log. Example: 1.5
 
  .INPUTS
    Parameters above
 
  .OUTPUTS
    Log file created
 
  .NOTES
    Version: 1.0
    Author: Luca Sturlese
    Creation Date: 10/05/12
    Purpose/Change: Initial function development
 
    Version: 1.1
    Author: Luca Sturlese
    Creation Date: 19/05/12
    Purpose/Change: Added debug mode support
 
  .EXAMPLE
    Log-Start -LogPath "C:\Windows\Temp" -LogName "Test_Script.log" -ScriptVersion "1.5"
  #>

    
  [CmdletBinding()]
  
  Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$LogName, [Parameter(Mandatory=$true)][string]$ScriptVersion)
  
  Process{
    $sFullPath = $LogPath + "\" + $LogName
    
    #Check if file exists and delete if it does
    If((Test-Path -Path $sFullPath)){
      Remove-Item -Path $sFullPath -Force
    }
    
    #Create file and start logging
    New-Item -Path $LogPath -Value $LogName -ItemType File
    
    Add-Content -Path $sFullPath -Value "***************************************************************************************************"
    Add-Content -Path $sFullPath -Value "Started processing at [$([DateTime]::Now)]."
    Add-Content -Path $sFullPath -Value "***************************************************************************************************"
    Add-Content -Path $sFullPath -Value ""
    Add-Content -Path $sFullPath -Value "Running script version [$ScriptVersion]."
    Add-Content -Path $sFullPath -Value ""
    Add-Content -Path $sFullPath -Value "***************************************************************************************************"
    Add-Content -Path $sFullPath -Value ""
  
    #Write to screen for debug mode
    Write-Debug "***************************************************************************************************"
    Write-Debug "Started processing at [$([DateTime]::Now)]."
    Write-Debug "***************************************************************************************************"
    Write-Debug ""
    Write-Debug "Running script version [$ScriptVersion]."
    Write-Debug ""
    Write-Debug "***************************************************************************************************"
    Write-Debug ""
  }
}

Function Log-Write{
  <#
  .SYNOPSIS
    Writes to a log file
 
  .DESCRIPTION
    Appends a new line to the end of the specified log file
   
  .PARAMETER LogPath
    Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log
   
  .PARAMETER LineValue
    Mandatory. The string that you want to write to the log
       
  .INPUTS
    Parameters above
 
  .OUTPUTS
    None
 
  .NOTES
    Version: 1.0
    Author: Luca Sturlese
    Creation Date: 10/05/12
    Purpose/Change: Initial function development
   
    Version: 1.1
    Author: Luca Sturlese
    Creation Date: 19/05/12
    Purpose/Change: Added debug mode support
 
  .EXAMPLE
    Log-Write -LogPath "C:\Windows\Temp\Test_Script.log" -LineValue "This is a new line which I am appending to the end of the log file."
  #>

  
  [CmdletBinding()]
  
  Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$LineValue)
  
  Process{
    Add-Content -Path $LogPath -Value $LineValue
  
    #Write to screen for debug mode
    Write-Debug $LineValue
  }
}

Function Log-Error{
  <#
  .SYNOPSIS
    Writes an error to a log file
 
  .DESCRIPTION
    Writes the passed error to a new line at the end of the specified log file
   
  .PARAMETER LogPath
    Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log
   
  .PARAMETER ErrorDesc
    Mandatory. The description of the error you want to pass (use $_.Exception)
   
  .PARAMETER ExitGracefully
    Mandatory. Boolean. If set to True, runs Log-Finish and then exits script
 
  .INPUTS
    Parameters above
 
  .OUTPUTS
    None
 
  .NOTES
    Version: 1.0
    Author: Luca Sturlese
    Creation Date: 10/05/12
    Purpose/Change: Initial function development
     
    Version: 1.1
    Author: Luca Sturlese
    Creation Date: 19/05/12
    Purpose/Change: Added debug mode support. Added -ExitGracefully parameter functionality
 
  .EXAMPLE
    Log-Error -LogPath "C:\Windows\Temp\Test_Script.log" -ErrorDesc $_.Exception -ExitGracefully $True
  #>

  
  [CmdletBinding()]
  
  Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$ErrorDesc, [Parameter(Mandatory=$true)][boolean]$ExitGracefully)
  
  Process{
    Add-Content -Path $LogPath -Value "Error: An error has occurred [$ErrorDesc]."
  
    #Write to screen for debug mode
    Write-Debug "Error: An error has occurred [$ErrorDesc]."
    
    #If $ExitGracefully = True then run Log-Finish and exit script
    If ($ExitGracefully -eq $True){
      Log-Finish -LogPath $LogPath
      Break
    }
  }
}

Function Log-Finish{
  <#
  .SYNOPSIS
    Write closing logging data & exit
 
  .DESCRIPTION
    Writes finishing logging data to specified log and then exits the calling script
   
  .PARAMETER LogPath
    Mandatory. Full path of the log file you want to write finishing data to. Example: C:\Windows\Temp\Test_Script.log
 
  .PARAMETER NoExit
    Optional. If this is set to True, then the function will not exit the calling script, so that further execution can occur
   
  .INPUTS
    Parameters above
 
  .OUTPUTS
    None
 
  .NOTES
    Version: 1.0
    Author: Luca Sturlese
    Creation Date: 10/05/12
    Purpose/Change: Initial function development
     
    Version: 1.1
    Author: Luca Sturlese
    Creation Date: 19/05/12
    Purpose/Change: Added debug mode support
   
    Version: 1.2
    Author: Luca Sturlese
    Creation Date: 01/08/12
    Purpose/Change: Added option to not exit calling script if required (via optional parameter)
 
  .EXAMPLE
    Log-Finish -LogPath "C:\Windows\Temp\Test_Script.log"
 
.EXAMPLE
    Log-Finish -LogPath "C:\Windows\Temp\Test_Script.log" -NoExit $True
  #>

  
  [CmdletBinding()]
  
  Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$false)][string]$NoExit)
  
  Process{
    Add-Content -Path $LogPath -Value ""
    Add-Content -Path $LogPath -Value "***************************************************************************************************"
    Add-Content -Path $LogPath -Value "Finished processing at [$([DateTime]::Now)]."
    Add-Content -Path $LogPath -Value "***************************************************************************************************"
  
    #Write to screen for debug mode
    Write-Debug ""
    Write-Debug "***************************************************************************************************"
    Write-Debug "Finished processing at [$([DateTime]::Now)]."
    Write-Debug "***************************************************************************************************"
  
    #Exit calling script if NoExit has not been specified or is set to False
    If(!($NoExit) -or ($NoExit -eq $False)){
      Exit
    }    
  }
}

Function Log-Email{
  <#
  .SYNOPSIS
    Emails log file to list of recipients
 
  .DESCRIPTION
    Emails the contents of the specified log file to a list of recipients
   
  .PARAMETER LogPath
    Mandatory. Full path of the log file you want to email. Example: C:\Windows\Temp\Test_Script.log
   
  .PARAMETER EmailFrom
    Mandatory. The email addresses of who you want to send the email from. Example: "admin@9to5IT.com"
 
  .PARAMETER EmailTo
    Mandatory. The email addresses of where to send the email to. Seperate multiple emails by ",". Example: "admin@9to5IT.com, test@test.com"
   
  .PARAMETER EmailSubject
    Mandatory. The subject of the email you want to send. Example: "Cool Script - [" + (Get-Date).ToShortDateString() + "]"
 
  .INPUTS
    Parameters above
 
  .OUTPUTS
    Email sent to the list of addresses specified
 
  .NOTES
    Version: 1.0
    Author: Luca Sturlese
    Creation Date: 05.10.12
    Purpose/Change: Initial function development
 
  .EXAMPLE
    Log-Email -LogPath "C:\Windows\Temp\Test_Script.log" -EmailFrom "admin@9to5IT.com" -EmailTo "admin@9to5IT.com, test@test.com" -EmailSubject "Cool Script - [" + (Get-Date).ToShortDateString() + "]"
  #>

  
  [CmdletBinding()]
  
  Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$EmailFrom, [Parameter(Mandatory=$true)][string]$EmailTo, [Parameter(Mandatory=$true)][string]$EmailSubject)
  
  Process{
    Try{
      $sBody = (Get-Content $LogPath | out-string)
      
      #Create SMTP object and send email
      $sSmtpServer = "smtp.yourserver"
      $oSmtp = new-object Net.Mail.SmtpClient($sSmtpServer)
      $oSmtp.Send($EmailFrom, $EmailTo, $EmailSubject, $sBody)
      Exit 0
    }
    
    Catch{
      Exit 1
    } 
  }
}

Function Add-VMwareModules {
<#
  .SYNOPSIS
    Loafs VMware PowerShell Modules
 
  .DESCRIPTION
    Loads VMware PowerShell Modules
    Requierments
    VMWare PowerCLI must be installed
    Latest version (6.3R1) can be found here - https://my.vmware.com/web/vmware/details?downloadGroup=PCLI630R1&productId=491
   
  .INPUTS
    None
 
  .OUTPUTS
    None
 
  .NOTES
    Version: 1.0
    Author: Omer Barel
    Creation Date: 06.09.16
    Purpose/Change: Initial function development
 
  .EXAMPLE
    Add-VMwareModules
  #>


  #### Loads All VMware Modules ####
    Import-Module VMware.VimAutomation.Cis.Core                                                                                                          
    Import-Module VMware.VimAutomation.Cloud                                                                                                             
    Import-Module VMware.VimAutomation.Common                                                                                                            
    Import-Module VMware.VimAutomation.Core                                                                                    
    Import-Module VMware.VimAutomation.HA                                                                                                                
    Import-Module VMware.VimAutomation.License                                                                                                           
    Import-Module VMware.VimAutomation.PCloud                                                                                                            
    Import-Module VMware.VimAutomation.SDK                                                                                                               
    Import-Module VMware.VimAutomation.Storage                                                                                                           
    Import-Module VMware.VimAutomation.Vds                                                                                                               
    Import-Module VMware.VimAutomation.vROps                                                                                                             
    Import-Module VMware.VumAutomation
}

#### Declares functions that are available ####

Write-Host "The below functions are avaialble. Use Get-Help {Function} -Full for instructions and details" -ForegroundColor Yellow -BackgroundColor DarkMagenta
Write-Host "1. Log-ScriptEvent" -ForegroundColor Yellow -BackgroundColor DarkMagenta
Write-Host "2. Log-Start" -ForegroundColor Yellow -BackgroundColor DarkMagenta
Write-Host "3. Log-Write" -ForegroundColor Yellow -BackgroundColor DarkMagenta
Write-Host "4. Log-Error" -ForegroundColor Yellow -BackgroundColor DarkMagenta
Write-Host "5. Log-Finish" -ForegroundColor Yellow -BackgroundColor DarkMagenta
Write-Host "6. Log-Email" -ForegroundColor Yellow -BackgroundColor DarkMagenta
Write-Host "7. Add-VMwareModules" -ForegroundColor Yellow -BackgroundColor DarkMagenta

#### Loads Script Template for quick start ###

$Template_Path = "Path to your script template"
$Pathexists = Test-Path $Template_Path
if ($Pathexists -eq $true) {
    psedit $Template_Path
}
else {
    write-host "Path to script template missing. Please check the path to the script template in your profile and modify accordingly!" -ForegroundColor Red -BackgroundColor Black
}