functions and the -property parameter

rated by 0 users
This post has 3 Replies | 3 Followers

Not Ranked
Posts 2
pbchris Posted: 05-03-2012 2:56 PM

Im fairly new to powershell and am starting to write my own functions. I am trying to figure out the writing of parameters in a function. I always see the -property parameter in the powershell cmdlets.

Is there anyway to duplicate a -property parameter in my functions? I cant find anything anywhere on this. I had thought about a parameter that does a select-object but i cant seem to make it work.

Any help would be appreciated

Top 100 Contributor
Posts 33

function foo($string,$string2,$string3){

  write-host $string
  write-host $string2
  write-host $string3
}

 

"foo a b c" would output
a
b
c
"foo -string a -string2 b -string3 c" would output
a
b
c

The neat thing is that you can scramble the order you input parameters.
"foo -string2 b -string a -string3 c" would output
a
b


To create a switch use
function foo([switch]$string){
  if($string){write-host "String switched on"}
}

The function will only return something if you write "foo -string" 

Top 10 Contributor
Posts 658
Idera Employee

It is generally accepted best practice starting with PowerShell v2 to use advanced function sytnax like this:

function foo(){

param(

  [string]$string,

  [string]$string2,

  [string]$string3

)

  write-host $string
  write-host $string2
  write-host $string3
}

It accomplishes the same goal but there are many other things you can do using this technique. You can read more about it by looking at the topic about_advanced_functions:

http://technet.microsoft.com/en-us/library/dd315326.aspx

 

Not Ranked
Posts 2

Thanks. Ill give this a shot and see what i can come up with.

Page 1 of 1 (4 items) | RSS
Copyright 2012 PowerShell.com. All rights reserved.