powershell

Running VMware vSphere PowerCLI scripts in Powershell

Add-PSSnapin VMware.VimAutomation.Core
Add-PSSnapin VMware.VimAutomation.Vds
if(get-item HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns\VMware.VimAutomation.Core){
	. ((get-item HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns\VMware.VimAutomation.Core).GetValue("ApplicationBase")+"\Scripts\Initialize-PowerCLIEnvironment.ps1")
}
else
{
	write-warning "PowerCLI Path not found in registry, please set path to Initialize-PowerCLIEnvironment.ps1 manually. Is PowerCli aleady installed?"

Starting and Stoping a Powershell Script as a Job

You may start your script as a job.

start-job -scriptblock {. Pathofyourscript.ps1}

Then stop the job if CTRL+C is pressed:

[console]::TreatControlCAsInput = $true
while ($true) {

     Start-Sleep -s 30

     if ([console]::KeyAvailable) {

         $key = [system.console]::readkey($true)
         if (($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "C")) { "Terminating..." }

    } 

        get-job | stop-job

        break
   }
    }
}

Get running PowerShell script Current Directory (function)

function Get-ScriptDirectory
{
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value;
    if($Invocation.PSScriptRoot)
    {
        $Invocation.PSScriptRoot;
    }
    Elseif($Invocation.MyCommand.Path)
    {
        Split-Path $Invocation.MyCommand.Path
    }
    else
    {
        $Invocation.InvocationName.Substring(0,$Invocation.InvocationName.LastIndexOf("\"));
    }
}

 

Powershell Error Handling

Based on original article that can be found here: http://powershell.com/cs/blogs/ebookv2/archive/2012/03/18/chapter-11-error-handling.aspx

When you design a PowerShell script, there may be situations where you cannot eliminate all possible runtime errors. If your script maps network drives, there could be a situation where no more drive letters are available, and when your script performs a remote WMI query, the remote machine may not be available.

Pages

Subscribe to RSS - powershell