Wednesday, 1 January 2014

PowerShell parameters

The following code shows two ways in PowerShell can check whether an optional parameter has been used or not.

This could be used in situations where most of the time the parameter is not used and on odd occasions we decide to use the parameter.

Of course, there are other ways in which we can check, but this is also a reminder of two ways to achieve this.




function foo {

[cmdletbinding()]
Param (
        [parameter(Mandatory=$false)]
        [String]
        $Param
      ) #end param

   Write-Host "This is function foo";

   # Method 1
   if ($Param) {
      Write-Host "(1)Parameter is use is: $Param";
   } else {
      Write-Host "No parameter used at one";
   }
   # Method 2
   if ($PSBoundParameters['Param']) {
      Write-Host "(2)Parameter is use is: $Param";
   } else {
      Write-Host "No parameter used at two";
   }

} #end of foo

foo some_info ;


Keywords: powershell parameters check

No comments:

Post a Comment