powershell

How to Run PowerShell Commands on Remote Computers

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?"

Windows Server 2012 R2 Update PowerShell Help

If one doesn`t return valid xml, you will see this error.

get
-module -listavailable  | select Name, HelpInfoUri

 

Working with Customization Specifications in PowerCLI

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
   }
    }
}

PowerShell : Using Try / Finally block to catch a Ctrl-C and cleanup

Cheat Sheet - .NET Framework Exceptions

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.

Powershell script termination examples

function Close-Script {
    #If stream1 is created
    if($stream1) { 
        $stream1.Close()
    }

    #Terminate script
    exit
}

$stream1 = New-Object System.IO.StreamWriter filename.txt


If(a test that detects your error) {
    Close-Script
}


Pages

Subscribe to RSS - powershell