Showing posts with label Parameters. Show all posts
Showing posts with label Parameters. Show all posts

January 6, 2014

Loading (import) a module with arguments

You can use the –ArgumentList parameter of the import-module cmdlet to pass arguments when loading a module.

You should use a param bloc in your module to define your parameters :

param(
    [parameter(Position=0,Mandatory=$false)][boolean]$BeQuiet=$true,
    [parameter(Position=1,Mandatory=$false)][string]$URL
)

Then call the import-module cmdlet like this :

import-module .\myModule.psm1 -ArgumentList $True,'http://www.microsoft.com'

As may have already noticed, you can only supply values (no names) to –ArgumentList. So you should define you parameters carefully with the position argument.

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

September 7, 2012

How to use ParameterSets in a CmdLet ?

Here’s a quick sample :

function test-param 
{ 
[CmdletBinding(DefaultParametersetName="p2")] 
param( 
[Parameter(ParameterSetName="p1",Position=0)] 
[String] 
$d, 

[Parameter(ParameterSetName="p2", Position=0)] 
[String]$i 
) 
    switch ($PsCmdlet.ParameterSetName) 
    { 
    "p1"  { Write-Host ([DateTime]$d); break} 
    "p2"  { Write-Host ([INT]$i); break} 
    } 
}

For the complete explanation : PowerShell V2: ParameterSets From Jeffrey Snover [MSFT] @ Windows PowerShell Blog