Showing posts with label Favorite. Show all posts
Showing posts with label Favorite. Show all posts

June 13, 2014

How to call a Powershell script from the command line and return an ERRORLEVEL

Sometimes you want to call a powershell script from the command line and get an ERRORLEVEL a the exit if an exception is throw in the script (ex: With a scheduled task).

In Powershell v2 you could do this :

powershell.exe -noprofile -command ". c:\test-exit.ps1 -erroraction stop;exit $LastExitCode"

Unfortunately this does not work anymore in Powershell v4 (always return ERRORLEVEL 0). It looks like the $LastExitCode is not define anymore for a script by Powershell (only for an external process).  But Powershell seems to now behave as expected and exit with an ERRORLEVEL=1 if any error occurs in your script. So now, the following code should works :

powershell.exe -noprofile -command ". c:\test-exit.ps1 -erroraction stop"

If you really want to check if your script was successful and return a special ERRORLEVEL, you should use the $? variable :

powershell.exe -noprofile -command ". c:\test-exit.ps1 -erroraction stop;if ($?){exit 0}else{exit 99}"

Don’t forget :

  • To use dote-sourcing, the small dot (.) in  front of the script name.
  • To use the –command parameter instead of the –file parameter. The two parameters behave differently.
  • To set the –erroraction stop. If you keep the default value of continue, your script will not stop and the ERRORLEVEL will not be set to 1.

February 13, 2013

How to add –whatif support to a function

 

Function Get-HelloWorld {
    [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact="Low")]
    param()
    $message="Hello world"
    if ($PSCmdlet.ShouldProcess($message,"Write-host")) {
        write-host $message
    }
  }

Get-HelloWorld -whatif will produce :

What if: Performing operation "Write-host" on Target "Hello world".

As a bonus, you will also be able to use the -confirm and –verbose parameter

April 7, 2010

How to get the script’s directory ?

Sometimes you want to know what directory you script is in, here’s a function that return that value :

function get-scriptdirectory {

# .SYNOPSIS 
# 	Return the current script directory path, compatible with PrimalScript 2009
# 	Equivalent to VBscript fso.GetParentFolderName(WScript.ScriptFullName)
# 	Requires PowerShell 2.0
#    
# .DESCRIPTION
#	Author   : Jean-Pierre.Paradis@fsa.ulaval.ca
#	Date     : March 31, 2010
#	Version  : 1.01
#
# .LINK 
# 	http://blog.sapien.com/index.php/2009/09/02/powershell-hosting-and-myinvocation/

    if (Test-Path variable:\hostinvocation) 
    	{$FullPath=$hostinvocation.MyCommand.Path}
    Else {
   		$FullPath=(get-variable myinvocation -scope script).value.Mycommand.Definition }  	
	if (Test-Path $FullPath) {
    	return (Split-Path $FullPath) 
		}
    Else {
		$FullPath=(Get-Location).path
		Write-Warning ("Get-ScriptDirectory: Powershell Host <" + $Host.name + "> may not be compatible with this function, the current directory <" + $FullPath + "> will be used.")
		return $FullPath
		}
}

How to create a collection of custom objects ?

First you have to create a collection object :

$psobjectStrongName = (New-Object psobject).psobject.GetType().AssemblyQualifiedName
$Col = New-Object "System.Collections.ObjectModel.Collection``1[[$psobjectStrongName]]"

Than you have to add an item (object) to the collection.

Method 1 :

$colItem = New-Object psobject -Property @{ObjRef=1;AddedBy="New-Object"}
$Col.Add($colItem)
$colItem =$null

Method 2 :

$colItem = New-Object psobject
Add-Member -InputObject $colItem -MemberType noteproperty -Name ObjRef -Value 2
Add-Member -InputObject $colItem -MemberType noteproperty -Name AddedBy -Value "Add-Member"
$Col.Add($colItem)
$colItem =$null

Method 3 (my personnal favorite) :

$Col.add((New-Object psobject -Property @{ObjRef=3;AddedBy="add with New-Object"}))

Source : http://www.vistax64.com/powershell/25307-how-put-psobject-into-system-collections-objectmodel-collection.html

How to send an email ?

$message = '<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"><html><head></head><body lang=FR-CA>This is the body of the message</body></html>"
send-MailMessage -to "toto@domain.com" -Encoding ([System.Text.Encoding]::UTF8) -subject "PowerShell Rocs" -from "bozo@domain.com"  -bodyasHTML -body $message -smtpserver "mysmtp.domain.com"

If you want to send your mail to multiple recipients, use the following syntax for the -to  parameter :

@("bozo@domain.com","toto@domain.com")