Lessons In PowerShell - Running a PowerShell Script Via Windows Task Scheduler

   Submit to Reddit      
  

In order to run a Windows PowerShell script through the Windows Task Scheduler:

  • Run the Task Scheduler:

    Start ➞ Control Panel ➞ Administrative Tools ➞ Task Scheduler

  • Create and schedule a task that starts a program.

    Specify the program to run as:

      C:\WINDOWS\system32\WindowsPowerShell\v1.0\Powershell.exe
    

    Specify the arguments as:

      C:\PathToMyScript\MyScript.ps1
    

The PowerShell script will now run as scheduled.

Lessons In PowerShell - Exception Handling

   Submit to Reddit      
  

The following useful information is primarily taken from the Windows PowerShell Language Quick Reference (QuadFold.rtf) documentation.

Throw

The keyword "Throw" allows an exception to be thrown. The argument for the Throw keyword can be a string, exception or ErrorRecord.

throw "Some description about the exception"

Traps

A trap is a mechanism to catch an exception, although it behave more like the Visual Basic 6 On Error functionality. The continue keyword will continue execution at the script statement after the one that caused the trap. $? is updated but no error record is generated. The break keyword will rethrow the exception.

Trap [ExceptionType] 
{
    if (...) 
    { 
        continue
    } else (...)
    { 
        break
    }

    # Doing nothing will do what is specified in the $ErrorActionPreference setting
}

Try / Catch / Finally

There is no native support in PowerShell Version 1 for the typical Try / Catch / Finally syntax found in other languages. However with the use of the & invoke operator, the Try / Catch / Finally syntax can be mimicked.

&{
     &{   # Try
          # Do your processing here
     } 
     trap # Catch
     {
         Write-Host "TRAPPED: " + $_.Exception.GetType().FullName
         Write-Host "TRAPPED: " + $_.Exception.Message
         continue   # So that the "Finally" stuff gets executed
     }
} #Finally
# Put your finally code here

However, from PowerShell Version 2, you can use the familiar try / catch syntax.

    try {
        ...
    } catch {
        ...
    }

Lessons In PowerShell - Functions

   Submit to Reddit      
  

The following useful information is primarily taken from the Windows PowerShell Language Quick Reference (QuadFold.rtf) documentation.

Functions

function MyFunction 
{
    write-object $args[0]
}

function test ([string] $label="default label", [int] $start=0)
{ 
    ...
}

Lessons In PowerShell - Escape Sequences

   Submit to Reddit      
  

The following useful information is primarily taken from the Windows PowerShell Language Quick Reference (QuadFold.rtf) documentation.

Escape Sequences

The escape character in Windows PowerShell is the backwards apostrophe.

Escape Sequence Description
`0 (null)
`a (alert)
`b (backspace)
`f (form feed)
`n (new line)
`r (carriage return)
`t (tab)
`v (vertical quote)